From a5e801f9c28cd7146d723d9e413ecb7308448da0 Mon Sep 17 00:00:00 2001 From: Pavel Slabko Date: Thu, 12 Feb 2026 12:56:04 +0100 Subject: [PATCH 1/5] update python sdk Strip any directory traversal --- docs/generators/crystal.md | 4 +- docs/generators/groovy.md | 2 - docs/generators/java-camel.md | 6 +- docs/generators/java-dubbo.md | 2 - docs/generators/java-helidon-client.md | 2 - docs/generators/java-helidon-server.md | 2 - docs/generators/java-inflector.md | 2 - docs/generators/java-micronaut-client.md | 2 - docs/generators/java-micronaut-server.md | 2 - docs/generators/java-microprofile.md | 2 - docs/generators/java-msf4j.md | 2 - docs/generators/java-pkmst.md | 2 - docs/generators/java-play-framework.md | 2 - docs/generators/java-undertow-server.md | 2 - docs/generators/java-vertx-web.md | 2 - docs/generators/java-vertx.md | 2 - docs/generators/java-wiremock.md | 2 - docs/generators/java.md | 2 - docs/generators/jaxrs-cxf-cdi.md | 2 - docs/generators/jaxrs-cxf-client.md | 2 - docs/generators/jaxrs-cxf-extended.md | 2 - docs/generators/jaxrs-cxf.md | 2 - docs/generators/jaxrs-jersey.md | 2 - docs/generators/jaxrs-resteasy-eap.md | 2 - docs/generators/jaxrs-resteasy.md | 2 - docs/generators/jaxrs-spec.md | 2 - docs/generators/kotlin-server.md | 7 +- docs/generators/kotlin-spring.md | 6 +- docs/generators/protobuf-schema.md | 1 - docs/generators/python-fastapi.md | 2 +- docs/generators/spring.md | 6 +- docs/generators/swift5.md | 2 +- docs/generators/typescript-angular.md | 4 +- docs/generators/typescript-axios.md | 2 +- docs/generators/typescript.md | 1 - .../main/resources/python/api_client.mustache | 2 +- samples/client/others/c/bearerAuth/README.md | 2 +- .../c/bearerAuth/include/keyValuePair.h | 17 -- .../petstore/ada/.openapi-generator/VERSION | 2 +- .../src/client/samples-petstore-clients.adb | 2 +- .../src/client/samples-petstore-clients.ads | 2 +- .../ada/src/model/samples-petstore-models.adb | 2 +- .../ada/src/model/samples-petstore-models.ads | 2 +- .../petstore/apex/.openapi-generator/VERSION | 2 +- samples/client/petstore/bash/docs/Name.md | 13 - .../c-useJsonUnformatted/model/order.c | 233 ------------------ samples/client/petstore/c/model/category.h | 40 --- .../.openapi-generator/VERSION | 2 +- .../avro-schema/.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../fastendpoints/.openapi-generator/VERSION | 2 +- .../src/Org.OpenAPITools/Program.cs | 33 --- .../src/Org.OpenAPITools/Program.cs | 33 --- .../src/Org.OpenAPITools/Program.cs | 33 --- .../src/Org.OpenAPITools/Program.cs | 33 --- .../src/Org.OpenAPITools/Program.cs | 33 --- .../src/Org.OpenAPITools/Program.cs | 33 --- .../Formatters/InputFormatterStream.cs | 45 ---- .../src/Org.OpenAPITools/Program.cs | 33 --- .../src/Org.OpenAPITools/Startup.cs | 150 ----------- .../src/Org.OpenAPITools/Program.cs | 33 --- .../src/Org.OpenAPITools/Program.cs | 33 --- .../src/Org.OpenAPITools/Program.cs | 33 --- .../src/Org.OpenAPITools/Program.cs | 33 --- .../Formatters/InputFormatterStream.cs | 45 ---- .../src/Org.OpenAPITools/Program.cs | 33 --- .../model/Category.cpp | 144 ----------- .../model/OuterType.cpp | 94 ------- 74 files changed, 30 insertions(+), 1272 deletions(-) diff --git a/docs/generators/crystal.md b/docs/generators/crystal.md index ea2b3cc400db..ba481b67e4da 100644 --- a/docs/generators/crystal.md +++ b/docs/generators/crystal.md @@ -94,7 +94,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • if
  • in
  • include
  • -
  • instance_sizeof
  • +
  • instance
  • is_a?
  • lib
  • macro
  • @@ -102,11 +102,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • next
  • nil
  • nil?
  • -
  • object_id
  • of
  • out
  • pointerof
  • -
  • previous_def
  • private
  • protected
  • require
  • diff --git a/docs/generators/groovy.md b/docs/generators/groovy.md index d5cdff849435..e2f1314c4bb1 100644 --- a/docs/generators/groovy.md +++ b/docs/generators/groovy.md @@ -30,12 +30,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-camel.md b/docs/generators/java-camel.md index 0651cc84e31d..b50d9b4728c1 100644 --- a/docs/generators/java-camel.md +++ b/docs/generators/java-camel.md @@ -44,13 +44,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configPackage|configuration package for generated code| |org.openapitools.configuration| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |delegatePattern|Whether to generate the server files using the delegate pattern| |false| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| @@ -87,7 +85,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |resourceFolder|resource folder for generated resources| |src/main/resources| |responseWrapper|wrap the responses in given type (Future, Callable, CompletableFuture,ListenableFuture, DeferredResult, RxObservable, RxSingle or fully qualified type)| |null| |returnSuccessCode|Generated server returns 2xx code| |false| -|schemaImplements|Ability to supply interfaces per schema that should be implemented (serves similar purpose as vendor extension `x-implements`, but is fully decoupled from the api spec). Example: yaml `schemaImplements: {Pet: com.some.pack.WithId, Category: [com.some.pack.CategoryInterface], Dog: [com.some.pack.Canine, com.some.pack.OtherInterface]}` implements interfaces in schemas `Pet` (interface `com.some.pack.WithId`), `Category` (interface `com.some.pack.CategoryInterface`), `Dog`(interfaces `com.some.pack.Canine`, `com.some.pack.OtherInterface`)| |empty map| |scmConnection|SCM connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git| |scmDeveloperConnection|SCM developer connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git| |scmUrl|SCM URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| @@ -112,14 +109,13 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useOptional|Use Optional container for optional parameters| |false| |useResponseEntity|Use the `ResponseEntity` type to wrap return values of generated API methods. If disabled, method are annotated using a `@ResponseStatus` annotation, which has the status of the first response declared in the Api definition| |true| |useSealed|Whether to generate sealed model interfaces and classes| |false| -|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot ≥ 3 (use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| +|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| |useSpringBuiltInValidation|Disable `@Validated` at the class level when using built-in validation.| |false| |useSpringController|Annotate the generated API as a Spring Controller| |false| |useSwaggerUI|Open the OpenApi specification in swagger-ui. Will also import and configure needed dependencies| |true| |useTags|use tags for creating interface and controller classnames| |false| |virtualService|Generates the virtual service. For more details refer - https://github.com/virtualansoftware/virtualan/wiki| |false| |withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false| -|xImplementsSkip|Ability to choose interfaces that should NOT be implemented in the models despite their presence in vendor extension `x-implements`. Takes a list of fully qualified interface names. Example: yaml `xImplementsSkip: [com.some.pack.WithPhotoUrls]` skips implementing the interface `com.some.pack.WithPhotoUrls` in any schema| |empty list| ## SUPPORTED VENDOR EXTENSIONS diff --git a/docs/generators/java-dubbo.md b/docs/generators/java-dubbo.md index 2ea83de8db02..fa64f3d35955 100644 --- a/docs/generators/java-dubbo.md +++ b/docs/generators/java-dubbo.md @@ -34,12 +34,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configPackage|configuration package for generated code| |org.openapitools.configuration| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-helidon-client.md b/docs/generators/java-helidon-client.md index 06f803388070..5f309c81ce6b 100644 --- a/docs/generators/java-helidon-client.md +++ b/docs/generators/java-helidon-client.md @@ -33,8 +33,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configKey|Config key in @RegisterRestClient. Default to none.| |null| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| diff --git a/docs/generators/java-helidon-server.md b/docs/generators/java-helidon-server.md index f456ed9ce064..b4d8db132743 100644 --- a/docs/generators/java-helidon-server.md +++ b/docs/generators/java-helidon-server.md @@ -32,8 +32,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| diff --git a/docs/generators/java-inflector.md b/docs/generators/java-inflector.md index 7054f33501ac..3adfffad38df 100644 --- a/docs/generators/java-inflector.md +++ b/docs/generators/java-inflector.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-micronaut-client.md b/docs/generators/java-micronaut-client.md index 645025f315d8..37a2d8907ee1 100644 --- a/docs/generators/java-micronaut-client.md +++ b/docs/generators/java-micronaut-client.md @@ -41,12 +41,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |dateFormat|Specify the format pattern of date as a string| |null| |dateLibrary|Option. Date library to use|
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| |datetimeFormat|Specify the format pattern of date-time as a string| |null| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-micronaut-server.md b/docs/generators/java-micronaut-server.md index 73fb9dd977ad..4a21268afbd5 100644 --- a/docs/generators/java-micronaut-server.md +++ b/docs/generators/java-micronaut-server.md @@ -36,12 +36,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |dateFormat|Specify the format pattern of date as a string| |null| |dateLibrary|Option. Date library to use|
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| |datetimeFormat|Specify the format pattern of date-time as a string| |null| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-microprofile.md b/docs/generators/java-microprofile.md index 7f87f275d343..9e02b37145ef 100644 --- a/docs/generators/java-microprofile.md +++ b/docs/generators/java-microprofile.md @@ -37,12 +37,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configKeyFromClassName|If true, set tag as key in @RegisterRestClient. Default to false. Only `microprofile` supports this option.| |null| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-msf4j.md b/docs/generators/java-msf4j.md index 25842d8df871..7251308c1440 100644 --- a/docs/generators/java-msf4j.md +++ b/docs/generators/java-msf4j.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-pkmst.md b/docs/generators/java-pkmst.md index fc5e849f837b..e2299587c5f2 100644 --- a/docs/generators/java-pkmst.md +++ b/docs/generators/java-pkmst.md @@ -33,12 +33,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-play-framework.md b/docs/generators/java-play-framework.md index f30134f8ec8c..c5f80ab75d16 100644 --- a/docs/generators/java-play-framework.md +++ b/docs/generators/java-play-framework.md @@ -35,12 +35,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |controllerOnly|Whether to generate only API interface stubs without the server files.| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-undertow-server.md b/docs/generators/java-undertow-server.md index 1356bc33f589..c258e9aa5df4 100644 --- a/docs/generators/java-undertow-server.md +++ b/docs/generators/java-undertow-server.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-vertx-web.md b/docs/generators/java-vertx-web.md index e4156c53a887..473c40d1af7d 100644 --- a/docs/generators/java-vertx-web.md +++ b/docs/generators/java-vertx-web.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-vertx.md b/docs/generators/java-vertx.md index 5a8d19f0ee4f..dd2722079b63 100644 --- a/docs/generators/java-vertx.md +++ b/docs/generators/java-vertx.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-wiremock.md b/docs/generators/java-wiremock.md index e6f238f31ffc..39b0a40d6edf 100644 --- a/docs/generators/java-wiremock.md +++ b/docs/generators/java-wiremock.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java.md b/docs/generators/java.md index 85da80e56a9e..b98c5386e4e5 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -37,12 +37,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configKeyFromClassName|If true, set tag as key in @RegisterRestClient. Default to false. Only `microprofile` supports this option.| |null| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-cxf-cdi.md b/docs/generators/jaxrs-cxf-cdi.md index eb7f94c2993d..02f6b177827e 100644 --- a/docs/generators/jaxrs-cxf-cdi.md +++ b/docs/generators/jaxrs-cxf-cdi.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-cxf-client.md b/docs/generators/jaxrs-cxf-client.md index bed567bf4f05..e735d8f0ef4b 100644 --- a/docs/generators/jaxrs-cxf-client.md +++ b/docs/generators/jaxrs-cxf-client.md @@ -33,12 +33,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-cxf-extended.md b/docs/generators/jaxrs-cxf-extended.md index 00971949946b..aeb82d2dce55 100644 --- a/docs/generators/jaxrs-cxf-extended.md +++ b/docs/generators/jaxrs-cxf-extended.md @@ -34,12 +34,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-cxf.md b/docs/generators/jaxrs-cxf.md index 7325c0b5965b..b9b120e2f8d9 100644 --- a/docs/generators/jaxrs-cxf.md +++ b/docs/generators/jaxrs-cxf.md @@ -34,12 +34,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-jersey.md b/docs/generators/jaxrs-jersey.md index 59186e03fa91..a5d3e9a3c51a 100644 --- a/docs/generators/jaxrs-jersey.md +++ b/docs/generators/jaxrs-jersey.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-resteasy-eap.md b/docs/generators/jaxrs-resteasy-eap.md index ce5dd75fe065..85a3ea082300 100644 --- a/docs/generators/jaxrs-resteasy-eap.md +++ b/docs/generators/jaxrs-resteasy-eap.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-resteasy.md b/docs/generators/jaxrs-resteasy.md index f451f945b804..c03831051659 100644 --- a/docs/generators/jaxrs-resteasy.md +++ b/docs/generators/jaxrs-resteasy.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-spec.md b/docs/generators/jaxrs-spec.md index a36ac50aef17..03c2d043bf78 100644 --- a/docs/generators/jaxrs-spec.md +++ b/docs/generators/jaxrs-spec.md @@ -32,12 +32,10 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md index 86859ea27401..733e819e6ce3 100644 --- a/docs/generators/kotlin-server.md +++ b/docs/generators/kotlin-server.md @@ -30,7 +30,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |featureHSTS|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |true| |featureMetrics|Enables metrics feature.| |true| |featureResources|Generates routes in a typed way, for both: constructing URLs and reading the parameters.| |true| -|fixJacksonJsonTypeInfoInheritance|When true (default), ensures Jackson polymorphism works correctly by: (1) always setting visible=true on @JsonTypeInfo, and (2) adding the discriminator property to child models with appropriate default values. When false, visible is only set to true if all children already define the discriminator property.| |true| |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| |interfaceOnly|Whether to generate only API interface stubs without the server files. This option is currently supported only when using jaxrs-spec library.| |false| |library|library template (sub-template)|
    **ktor**
    ktor framework
    **ktor2**
    ktor (2.x) framework
    **jaxrs-spec**
    JAX-RS spec only
    **javalin5**
    Javalin 5
    **javalin6**
    Javalin 6
    |ktor| @@ -263,11 +262,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl | ---- | --------- | ---------- | |Simple|✓|OAS2,OAS3 |Composite|✓|OAS2,OAS3 -|Polymorphism|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 |Union|✗|OAS3 -|allOf|✓|OAS2,OAS3 +|allOf|✗|OAS2,OAS3 |anyOf|✗|OAS3 -|oneOf|✓|OAS3 +|oneOf|✗|OAS3 |not|✗|OAS3 ### Security Feature diff --git a/docs/generators/kotlin-spring.md b/docs/generators/kotlin-spring.md index 0c4e836ad7fa..9dfba5d3e6c8 100644 --- a/docs/generators/kotlin-spring.md +++ b/docs/generators/kotlin-spring.md @@ -43,8 +43,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |parcelizeModels|toggle "@Parcelize" for generated models| |null| |reactive|use coroutines for reactive behavior| |false| |requestMappingMode|Where to generate the class level @RequestMapping annotation.|
    **api_interface**
    Generate the @RequestMapping annotation on the generated Api Interface.
    **controller**
    Generate the @RequestMapping annotation on the generated Api Controller Implementation.
    **none**
    Do not add a class level @RequestMapping annotation.
    |controller| -|schemaImplements|A map of single interface or a list of interfaces per schema name that should be implemented (serves similar purpose as `x-kotlin-implements`, but is fully decoupled from the api spec). Example: yaml `schemaImplements: {Pet: com.some.pack.WithId, Category: [com.some.pack.CategoryInterface], Dog: [com.some.pack.Canine, com.some.pack.OtherInterface]}` implements interfaces in schemas `Pet` (interface `com.some.pack.WithId`), `Category` (interface `com.some.pack.CategoryInterface`), `Dog`(interfaces `com.some.pack.Canine`, `com.some.pack.OtherInterface`)| |empty map| -|schemaImplementsFields|A map of single field or a list of fields per schema name that should be prepended with `override` (serves similar purpose as `x-kotlin-implements-fields`, but is fully decoupled from the api spec). Example: yaml `schemaImplementsFields: {Pet: id, Category: [name, id], Dog: [bark, breed]}` marks fields to be prepended with `override` in schemas `Pet` (field `id`), `Category` (fields `name`, `id`) and `Dog` (fields `bark`, `breed`)| |empty map| |serializableModel|boolean - toggle "implements Serializable" for generated models| |null| |serverPort|configuration the port in which the sever is to run on| |8080| |serviceImplementation|generate stub service implementations that extends service interfaces. If this is set to true service interfaces will also be generated| |false| @@ -58,11 +56,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useFeignClientUrl|Whether to generate Feign client with url parameter.| |true| |useFlowForArrayReturnType|Whether to use Flow for array/collection return types when reactive is enabled. If false, will use List instead.| |true| |useResponseEntity|Whether (when false) to return actual type (e.g. List<Fruit>) and handle non-happy path responses via exceptions flow or (when true) return entire ResponseEntity (e.g. ResponseEntity<List<Fruit>>). If disabled, method are annotated using a @ResponseStatus annotation, which has the status of the first response declared in the Api definition| |true| -|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot ≥ 3 (use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| +|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| |useSwaggerUI|Open the OpenApi specification in swagger-ui. Will also import and configure needed dependencies| |true| |useTags|Whether to use tags for creating interface and controller class names| |false| -|xKotlinImplementsFieldsSkip|A list of fields per schema name that should NOT be created with `override` keyword despite their presence in vendor extension `x-kotlin-implements-fields` for the schema. Example: yaml `xKotlinImplementsFieldsSkip: Pet: [photoUrls]` skips `override` for `photoUrls` in schema `Pet`| |empty map| -|xKotlinImplementsSkip|A list of fully qualified interfaces that should NOT be implemented despite their presence in vendor extension `x-kotlin-implements`. Example: yaml `xKotlinImplementsSkip: [com.some.pack.WithPhotoUrls]` skips implementing the interface in any schema| |empty list| ## SUPPORTED VENDOR EXTENSIONS diff --git a/docs/generators/protobuf-schema.md b/docs/generators/protobuf-schema.md index e01683760038..fc8616619336 100644 --- a/docs/generators/protobuf-schema.md +++ b/docs/generators/protobuf-schema.md @@ -22,7 +22,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |aggregateModelsName|Aggregated model filename. If set, all generated models will be combined into this single file.| |null| |customOptionsApi|Custom options for the api files.| |null| |customOptionsModel|Custom options for the model files.| |null| -|extractEnumsToSeparateFiles|Extract enums to separate protobuf files and import them in models| |false| |numberedFieldNumberList|Field numbers in order.| |false| |startEnumsWithUnspecified|Introduces "UNSPECIFIED" as the first element of enumerations.| |false| |supportMultipleResponses|Support multiple responses| |true| diff --git a/docs/generators/python-fastapi.md b/docs/generators/python-fastapi.md index 4e706a4c1a52..5a87a2fcee28 100644 --- a/docs/generators/python-fastapi.md +++ b/docs/generators/python-fastapi.md @@ -10,7 +10,7 @@ title: Documentation for the python-fastapi Generator | generator stability | BETA | | | generator type | SERVER | | | generator language | Python | | -| generator language version | 3.10 | | +| generator language version | 3.7 | | | generator default templating engine | mustache | | | helpTxt | Generates a Python FastAPI server (beta). Models are defined with the pydantic library | | diff --git a/docs/generators/spring.md b/docs/generators/spring.md index 854118300bda..2af0fe826a3e 100644 --- a/docs/generators/spring.md +++ b/docs/generators/spring.md @@ -37,13 +37,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configPackage|configuration package for generated code| |org.openapitools.configuration| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| -|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |delegatePattern|Whether to generate the server files using the delegate pattern| |false| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| -|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| @@ -80,7 +78,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |resourceFolder|resource folder for generated resources| |src/main/resources| |responseWrapper|wrap the responses in given type (Future, Callable, CompletableFuture,ListenableFuture, DeferredResult, RxObservable, RxSingle or fully qualified type)| |null| |returnSuccessCode|Generated server returns 2xx code| |false| -|schemaImplements|Ability to supply interfaces per schema that should be implemented (serves similar purpose as vendor extension `x-implements`, but is fully decoupled from the api spec). Example: yaml `schemaImplements: {Pet: com.some.pack.WithId, Category: [com.some.pack.CategoryInterface], Dog: [com.some.pack.Canine, com.some.pack.OtherInterface]}` implements interfaces in schemas `Pet` (interface `com.some.pack.WithId`), `Category` (interface `com.some.pack.CategoryInterface`), `Dog`(interfaces `com.some.pack.Canine`, `com.some.pack.OtherInterface`)| |empty map| |scmConnection|SCM connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git| |scmDeveloperConnection|SCM developer connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git| |scmUrl|SCM URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| @@ -105,14 +102,13 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useOptional|Use Optional container for optional parameters| |false| |useResponseEntity|Use the `ResponseEntity` type to wrap return values of generated API methods. If disabled, method are annotated using a `@ResponseStatus` annotation, which has the status of the first response declared in the Api definition| |true| |useSealed|Whether to generate sealed model interfaces and classes| |false| -|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot ≥ 3 (use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| +|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| |useSpringBuiltInValidation|Disable `@Validated` at the class level when using built-in validation.| |false| |useSpringController|Annotate the generated API as a Spring Controller| |false| |useSwaggerUI|Open the OpenApi specification in swagger-ui. Will also import and configure needed dependencies| |true| |useTags|use tags for creating interface and controller classnames| |false| |virtualService|Generates the virtual service. For more details refer - https://github.com/virtualansoftware/virtualan/wiki| |false| |withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false| -|xImplementsSkip|Ability to choose interfaces that should NOT be implemented in the models despite their presence in vendor extension `x-implements`. Takes a list of fully qualified interface names. Example: yaml `xImplementsSkip: [com.some.pack.WithPhotoUrls]` skips implementing the interface `com.some.pack.WithPhotoUrls` in any schema| |empty list| ## SUPPORTED VENDOR EXTENSIONS diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index 68376d466186..9d565bf5993f 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -7,7 +7,7 @@ title: Documentation for the swift5 Generator | Property | Value | Notes | | -------- | ----- | ----- | | generator name | swift5 | pass this to the generate command after -g | -| generator stability | DEPRECATED | | +| generator stability | STABLE | | | generator type | CLIENT | | | generator language | Swift | | | generator default templating engine | mustache | | diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index f9f96573a4af..7d7c88af9979 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -11,7 +11,7 @@ title: Documentation for the typescript-angular Generator | generator type | CLIENT | | | generator language | Typescript | | | generator default templating engine | mustache | | -| helpTxt | Generates a TypeScript Angular (9.x - 21.x) client library. | | +| helpTxt | Generates a TypeScript Angular (9.x - 20.x) client library. | | ## CONFIG OPTIONS These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. @@ -34,7 +34,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |modelSuffix|The suffix of the generated model.| |null| |ngPackagrVersion|The version of ng-packagr compatible with Angular (see ngVersion option).| |null| -|ngVersion|The version of Angular. (At least 9.0.0)| |21.0.0| +|ngVersion|The version of Angular. (At least 9.0.0)| |20.0.0| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/docs/generators/typescript-axios.md b/docs/generators/typescript-axios.md index 62f77eca1828..269c2b09587e 100644 --- a/docs/generators/typescript-axios.md +++ b/docs/generators/typescript-axios.md @@ -20,7 +20,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |apiPackage|package for generated api classes| |null| -|axiosVersion|Use this property to override the axios version in package.json| |^1.13.5| +|axiosVersion|Use this property to override the axios version in package.json| |^1.6.1| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names.| |Enum| diff --git a/docs/generators/typescript.md b/docs/generators/typescript.md index 8616f926108d..5634f424a966 100644 --- a/docs/generators/typescript.md +++ b/docs/generators/typescript.md @@ -42,7 +42,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |supportsES6|Generate code that conforms to ES6.| |false| -|typescriptMajorVersion|Specify the major version of TypeScript to use in the client code. Default is 5.| |5| |useErasableSyntax|Use erasable syntax for the generated code. This is a temporary feature and will be removed in the future.| |false| |useInversify|Enable this to generate decorators and service identifiers for the InversifyJS inversion of control container. If you set 'deno' as 'platform', the generator will process this value as 'disable'.| |false| |useObjectParameters|Use aggregate parameter objects as function arguments for api operations instead of passing each parameter as a separate function argument.| |false| diff --git a/modules/openapi-generator/src/main/resources/python/api_client.mustache b/modules/openapi-generator/src/main/resources/python/api_client.mustache index 6a75de836518..8997e839ea0c 100644 --- a/modules/openapi-generator/src/main/resources/python/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/python/api_client.mustache @@ -724,7 +724,7 @@ class ApiClient: content_disposition ) assert m is not None, "Unexpected 'content-disposition' header value" - filename = m.group(1) + filename = os.path.basename(m.group(1)) # Strip any directory traversal path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/client/others/c/bearerAuth/README.md b/samples/client/others/c/bearerAuth/README.md index fb04f51e2c7a..2875a52718b2 100644 --- a/samples/client/others/c/bearerAuth/README.md +++ b/samples/client/others/c/bearerAuth/README.md @@ -5,7 +5,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat - API version: 0.1.9 - Package version: -- Generator version: 7.20.0-SNAPSHOT +- Generator version: 7.19.0-SNAPSHOT - Build package: org.openapitools.codegen.languages.CLibcurlClientCodegen ## Installation diff --git a/samples/client/others/c/bearerAuth/include/keyValuePair.h b/samples/client/others/c/bearerAuth/include/keyValuePair.h index cb839f29cdcf..e69de29bb2d1 100644 --- a/samples/client/others/c/bearerAuth/include/keyValuePair.h +++ b/samples/client/others/c/bearerAuth/include/keyValuePair.h @@ -1,17 +0,0 @@ -#ifndef _keyValuePair_H_ -#define _keyValuePair_H_ - -#include - -typedef struct keyValuePair_t { - char* key; - void* value; -} keyValuePair_t; - -keyValuePair_t *keyValuePair_create(char *key, void *value); - -keyValuePair_t* keyValuePair_create_allocate(char* key, double value); - -void keyValuePair_free(keyValuePair_t *keyValuePair); - -#endif /* _keyValuePair_H_ */ \ No newline at end of file diff --git a/samples/client/petstore/ada/.openapi-generator/VERSION b/samples/client/petstore/ada/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/client/petstore/ada/.openapi-generator/VERSION +++ b/samples/client/petstore/ada/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/client/petstore/ada/src/client/samples-petstore-clients.adb b/samples/client/petstore/ada/src/client/samples-petstore-clients.adb index 1ae7faf60e86..03cbbb4abc2f 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-clients.adb +++ b/samples/client/petstore/ada/src/client/samples-petstore-clients.adb @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.20.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.19.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/ada/src/client/samples-petstore-clients.ads b/samples/client/petstore/ada/src/client/samples-petstore-clients.ads index 36fa9c1fe37c..9939509f8a12 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-clients.ads +++ b/samples/client/petstore/ada/src/client/samples-petstore-clients.ads @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.20.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.19.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/ada/src/model/samples-petstore-models.adb b/samples/client/petstore/ada/src/model/samples-petstore-models.adb index e4a88a95e039..6e96402c2a80 100644 --- a/samples/client/petstore/ada/src/model/samples-petstore-models.adb +++ b/samples/client/petstore/ada/src/model/samples-petstore-models.adb @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.20.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.19.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/ada/src/model/samples-petstore-models.ads b/samples/client/petstore/ada/src/model/samples-petstore-models.ads index f4e05c36ca48..1a72c99d4f72 100644 --- a/samples/client/petstore/ada/src/model/samples-petstore-models.ads +++ b/samples/client/petstore/ada/src/model/samples-petstore-models.ads @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.20.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.19.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/apex/.openapi-generator/VERSION b/samples/client/petstore/apex/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/client/petstore/apex/.openapi-generator/VERSION +++ b/samples/client/petstore/apex/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/client/petstore/bash/docs/Name.md b/samples/client/petstore/bash/docs/Name.md index 295812c7bb7e..e69de29bb2d1 100644 --- a/samples/client/petstore/bash/docs/Name.md +++ b/samples/client/petstore/bash/docs/Name.md @@ -1,13 +0,0 @@ -# Name - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **integer** | | [default to null] -**snakeUnderscorecase** | **integer** | | [optional] [readonly] [default to null] -**property** | **string** | | [optional] [default to null] -**123Number** | **integer** | | [optional] [readonly] [default to null] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/client/petstore/c-useJsonUnformatted/model/order.c b/samples/client/petstore/c-useJsonUnformatted/model/order.c index d67d1d47c714..e69de29bb2d1 100644 --- a/samples/client/petstore/c-useJsonUnformatted/model/order.c +++ b/samples/client/petstore/c-useJsonUnformatted/model/order.c @@ -1,233 +0,0 @@ -#include -#include -#include -#include "order.h" - - -char* order_status_ToString(openapi_petstore_order_STATUS_e status) { - char* statusArray[] = { "NULL", "placed", "approved", "delivered" }; - return statusArray[status]; -} - -openapi_petstore_order_STATUS_e order_status_FromString(char* status){ - int stringToReturn = 0; - char *statusArray[] = { "NULL", "placed", "approved", "delivered" }; - size_t sizeofArray = sizeof(statusArray) / sizeof(statusArray[0]); - while(stringToReturn < sizeofArray) { - if(strcmp(status, statusArray[stringToReturn]) == 0) { - return stringToReturn; - } - stringToReturn++; - } - return 0; -} - -static order_t *order_create_internal( - long id, - long pet_id, - int quantity, - char *ship_date, - openapi_petstore_order_STATUS_e status, - int complete - ) { - order_t *order_local_var = malloc(sizeof(order_t)); - if (!order_local_var) { - return NULL; - } - order_local_var->id = id; - order_local_var->pet_id = pet_id; - order_local_var->quantity = quantity; - order_local_var->ship_date = ship_date; - order_local_var->status = status; - order_local_var->complete = complete; - - order_local_var->_library_owned = 1; - return order_local_var; -} - -__attribute__((deprecated)) order_t *order_create( - long id, - long pet_id, - int quantity, - char *ship_date, - openapi_petstore_order_STATUS_e status, - int complete - ) { - return order_create_internal ( - id, - pet_id, - quantity, - ship_date, - status, - complete - ); -} - -void order_free(order_t *order) { - if(NULL == order){ - return ; - } - if(order->_library_owned != 1){ - fprintf(stderr, "WARNING: %s() does NOT free objects allocated by the user\n", "order_free"); - return ; - } - listEntry_t *listEntry; - if (order->ship_date) { - free(order->ship_date); - order->ship_date = NULL; - } - free(order); -} - -cJSON *order_convertToJSON(order_t *order) { - cJSON *item = cJSON_CreateObject(); - - // order->id - if(order->id) { - if(cJSON_AddNumberToObject(item, "id", order->id) == NULL) { - goto fail; //Numeric - } - } - - - // order->pet_id - if(order->pet_id) { - if(cJSON_AddNumberToObject(item, "petId", order->pet_id) == NULL) { - goto fail; //Numeric - } - } - - - // order->quantity - if(order->quantity) { - if(cJSON_AddNumberToObject(item, "quantity", order->quantity) == NULL) { - goto fail; //Numeric - } - } - - - // order->ship_date - if(order->ship_date) { - if(cJSON_AddStringToObject(item, "shipDate", order->ship_date) == NULL) { - goto fail; //Date-Time - } - } - - - // order->status - if(order->status != openapi_petstore_order_STATUS_NULL) { - if(cJSON_AddStringToObject(item, "status", order_status_ToString(order->status)) == NULL) - { - goto fail; //Enum - } - } - - - // order->complete - if(order->complete) { - if(cJSON_AddBoolToObject(item, "complete", order->complete) == NULL) { - goto fail; //Bool - } - } - - return item; -fail: - if (item) { - cJSON_Delete(item); - } - return NULL; -} - -order_t *order_parseFromJSON(cJSON *orderJSON){ - - order_t *order_local_var = NULL; - - // order->id - cJSON *id = cJSON_GetObjectItemCaseSensitive(orderJSON, "id"); - if (cJSON_IsNull(id)) { - id = NULL; - } - if (id) { - if(!cJSON_IsNumber(id)) - { - goto end; //Numeric - } - } - - // order->pet_id - cJSON *pet_id = cJSON_GetObjectItemCaseSensitive(orderJSON, "petId"); - if (cJSON_IsNull(pet_id)) { - pet_id = NULL; - } - if (pet_id) { - if(!cJSON_IsNumber(pet_id)) - { - goto end; //Numeric - } - } - - // order->quantity - cJSON *quantity = cJSON_GetObjectItemCaseSensitive(orderJSON, "quantity"); - if (cJSON_IsNull(quantity)) { - quantity = NULL; - } - if (quantity) { - if(!cJSON_IsNumber(quantity)) - { - goto end; //Numeric - } - } - - // order->ship_date - cJSON *ship_date = cJSON_GetObjectItemCaseSensitive(orderJSON, "shipDate"); - if (cJSON_IsNull(ship_date)) { - ship_date = NULL; - } - if (ship_date) { - if(!cJSON_IsString(ship_date) && !cJSON_IsNull(ship_date)) - { - goto end; //DateTime - } - } - - // order->status - cJSON *status = cJSON_GetObjectItemCaseSensitive(orderJSON, "status"); - if (cJSON_IsNull(status)) { - status = NULL; - } - openapi_petstore_order_STATUS_e statusVariable; - if (status) { - if(!cJSON_IsString(status)) - { - goto end; //Enum - } - statusVariable = order_status_FromString(status->valuestring); - } - - // order->complete - cJSON *complete = cJSON_GetObjectItemCaseSensitive(orderJSON, "complete"); - if (cJSON_IsNull(complete)) { - complete = NULL; - } - if (complete) { - if(!cJSON_IsBool(complete)) - { - goto end; //Bool - } - } - - - order_local_var = order_create_internal ( - id ? id->valuedouble : 0, - pet_id ? pet_id->valuedouble : 0, - quantity ? quantity->valuedouble : 0, - ship_date && !cJSON_IsNull(ship_date) ? strdup(ship_date->valuestring) : NULL, - status ? statusVariable : openapi_petstore_order_STATUS_NULL, - complete ? complete->valueint : 0 - ); - - return order_local_var; -end: - return NULL; - -} diff --git a/samples/client/petstore/c/model/category.h b/samples/client/petstore/c/model/category.h index bd27e27e35a3..e69de29bb2d1 100644 --- a/samples/client/petstore/c/model/category.h +++ b/samples/client/petstore/c/model/category.h @@ -1,40 +0,0 @@ -/* - * category.h - * - * A category for a pet - */ - -#ifndef _category_H_ -#define _category_H_ - -#include -#include "../external/cJSON.h" -#include "../include/list.h" -#include "../include/keyValuePair.h" -#include "../include/binary.h" - -typedef struct category_t category_t; - - - - -typedef struct category_t { - long id; //numeric - char *name; // string - - int _library_owned; // Is the library responsible for freeing this object? -} category_t; - -__attribute__((deprecated)) category_t *category_create( - long id, - char *name -); - -void category_free(category_t *category); - -category_t *category_parseFromJSON(cJSON *categoryJSON); - -cJSON *category_convertToJSON(category_t *category); - -#endif /* _category_H_ */ - diff --git a/samples/openapi3/schema/petstore/avro-schema-issue6268/.openapi-generator/VERSION b/samples/openapi3/schema/petstore/avro-schema-issue6268/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/openapi3/schema/petstore/avro-schema-issue6268/.openapi-generator/VERSION +++ b/samples/openapi3/schema/petstore/avro-schema-issue6268/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION b/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION +++ b/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION +++ b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useApiVersioning/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useApiVersioning/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useApiVersioning/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useApiVersioning/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useAuthentication/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useAuthentication/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useAuthentication/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useAuthentication/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useProblemDetails/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useProblemDetails/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useProblemDetails/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useProblemDetails/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useRecords/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useRecords/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useRecords/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useRecords/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useResponseCaching/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useResponseCaching/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useResponseCaching/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useResponseCaching/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useValidators/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useValidators/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useValidators/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useValidators/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/server/petstore/aspnet/fastendpoints/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs index 18796da30fcb..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs +++ b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs @@ -1,45 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System; -using System.IO; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc.Formatters; - -namespace Org.OpenAPITools.Formatters -{ - /// - public class InputFormatterStream : InputFormatter - { - /// - public InputFormatterStream() - { - SupportedMediaTypes.Add("application/octet-stream"); - SupportedMediaTypes.Add("image/jpeg"); - } - - /// - public override Task ReadRequestBodyAsync(InputFormatterContext context) - { - return InputFormatterResult.SuccessAsync(context.HttpContext.Request.Body); - } - - /// - protected override bool CanReadType(Type type) - { - if (type == typeof(Stream)) - { - return true; - } - - return false; - } - } -} \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Startup.cs b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Startup.cs index bf30e991889e..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Startup.cs +++ b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Startup.cs @@ -1,150 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System; -using System.IO; -using System.Reflection; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.OpenApi.Models; -using System.Text.Json; -using System.Text.Json.Serialization; -using Org.OpenAPITools.Authentication; -using Org.OpenAPITools.Filters; -using Org.OpenAPITools.OpenApi; -using Org.OpenAPITools.Formatters; - -namespace Org.OpenAPITools -{ - /// - /// Startup - /// - public class Startup - { - /// - /// Constructor - /// - /// - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - /// - /// The application configuration. - /// - public IConfiguration Configuration { get; } - - /// - /// This method gets called by the runtime. Use this method to add services to the container. - /// - /// - public void ConfigureServices(IServiceCollection services) - { - services.AddTransient(); - services.AddAuthorization(authConfig => - { - authConfig.AddPolicy("api_key", policyBuilder => - { - policyBuilder - .AddRequirements(new ApiKeyRequirement(new[] { "my-secret-key" },"api_key")); - }); - }); - - // Add framework services. - services - // Don't need the full MVC stack for an API, see https://andrewlock.net/comparing-startup-between-the-asp-net-core-3-templates/ - .AddControllers(options => { - options.InputFormatters.Insert(0, new InputFormatterStream()); - }) - .AddJsonOptions(options => - { - options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; - options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); - }); - services - .AddSwaggerGen(c => - { - c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true); - - c.SwaggerDoc("1.0.0", new OpenApiInfo - { - Title = "OpenAPI Petstore", - Description = "OpenAPI Petstore (ASP.NET Core 8.0)", - TermsOfService = new Uri("https://github.com/openapitools/openapi-generator"), - Contact = new OpenApiContact - { - Name = "OpenAPI-Generator Contributors", - Url = new Uri("https://github.com/openapitools/openapi-generator"), - Email = "" - }, - License = new OpenApiLicense - { - Name = "NoLicense", - Url = new Uri("https://www.apache.org/licenses/LICENSE-2.0.html") - }, - Version = "1.0.0", - }); - c.CustomSchemaIds(type => type.FriendlyId(true)); - c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{Assembly.GetExecutingAssembly().GetName().Name}.xml"); - // Sets the basePath property in the OpenAPI document generated - c.DocumentFilter("/v2"); - - // Include DataAnnotation attributes on Controller Action parameters as OpenAPI validation rules (e.g required, pattern, ..) - // Use [ValidateModelState] on Actions to actually validate it in C# as well! - c.OperationFilter(); - }); - } - - /// - /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - /// - /// - /// - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseHsts(); - } - - app.UseHttpsRedirection(); - app.UseDefaultFiles(); - app.UseStaticFiles(); - app.UseSwagger(c => - { - c.RouteTemplate = "openapi/{documentName}/openapi.json"; - }) - .UseSwaggerUI(c => - { - // set route prefix to openapi, e.g. http://localhost:8080/openapi/index.html - c.RoutePrefix = "openapi"; - //TODO: Either use the SwaggerGen generated OpenAPI contract (generated from C# classes) - c.SwaggerEndpoint("/openapi/1.0.0/openapi.json", "OpenAPI Petstore"); - - //TODO: Or alternatively use the original OpenAPI contract that's included in the static files - // c.SwaggerEndpoint("/openapi-original.json", "OpenAPI Petstore Original"); - }); - app.UseRouting(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); - } - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs index 18796da30fcb..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs +++ b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs @@ -1,45 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System; -using System.IO; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc.Formatters; - -namespace Org.OpenAPITools.Formatters -{ - /// - public class InputFormatterStream : InputFormatter - { - /// - public InputFormatterStream() - { - SupportedMediaTypes.Add("application/octet-stream"); - SupportedMediaTypes.Add("image/jpeg"); - } - - /// - public override Task ReadRequestBodyAsync(InputFormatterContext context) - { - return InputFormatterResult.SuccessAsync(context.HttpContext.Request.Body); - } - - /// - protected override bool CanReadType(Type type) - { - if (type == typeof(Stream)) - { - return true; - } - - return false; - } - } -} \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Program.cs index 00ed16ed6758..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Program.cs @@ -1,33 +0,0 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Hosting; - -namespace Org.OpenAPITools -{ - /// - /// Program - /// - public class Program - { - /// - /// Main - /// - /// - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - /// - /// Create the host builder. - /// - /// - /// IHostBuilder - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup() - .UseUrls("http://0.0.0.0:8080/"); - }); - } -} diff --git a/samples/server/petstore/cpp-pistache-everything/model/Category.cpp b/samples/server/petstore/cpp-pistache-everything/model/Category.cpp index bd76b4cd6630..e69de29bb2d1 100644 --- a/samples/server/petstore/cpp-pistache-everything/model/Category.cpp +++ b/samples/server/petstore/cpp-pistache-everything/model/Category.cpp @@ -1,144 +0,0 @@ -/** -* OpenAPI Petstore -* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ - - -#include "Category.h" -#include "Helpers.h" - -#include - -namespace org::openapitools::server::model -{ - -Category::Category() -{ - m_Id = 0L; - m_IdIsSet = false; - m_Name = ""; - m_NameIsSet = false; - -} - -void Category::validate() const -{ - std::stringstream msg; - if (!validate(msg)) - { - throw org::openapitools::server::helpers::ValidationException(msg.str()); - } -} - -bool Category::validate(std::stringstream& msg) const -{ - return validate(msg, ""); -} - -bool Category::validate(std::stringstream& msg, const std::string& pathPrefix) const -{ - bool success = true; - const std::string _pathPrefix = pathPrefix.empty() ? "Category" : pathPrefix; - - - if (nameIsSet()) - { - const std::string& value = m_Name; - const std::string currentValuePath = _pathPrefix + ".name"; - - - - } - - return success; -} - -bool Category::operator==(const Category& rhs) const -{ - return - - - - ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && - - - ((!nameIsSet() && !rhs.nameIsSet()) || (nameIsSet() && rhs.nameIsSet() && getName() == rhs.getName())) - - ; -} - -bool Category::operator!=(const Category& rhs) const -{ - return !(*this == rhs); -} - -void to_json(nlohmann::json& j, const Category& o) -{ - j = nlohmann::json::object(); - if(o.idIsSet()) - j["id"] = o.m_Id; - if(o.nameIsSet()) - j["name"] = o.m_Name; - -} - -void from_json(const nlohmann::json& j, Category& o) -{ - if(j.find("id") != j.end()) - { - j.at("id").get_to(o.m_Id); - o.m_IdIsSet = true; - } - if(j.find("name") != j.end()) - { - j.at("name").get_to(o.m_Name); - o.m_NameIsSet = true; - } - -} - -int64_t Category::getId() const -{ - return m_Id; -} -void Category::setId(int64_t const value) -{ - m_Id = value; - m_IdIsSet = true; -} -bool Category::idIsSet() const -{ - return m_IdIsSet; -} -void Category::unsetId() -{ - m_IdIsSet = false; -} -std::string Category::getName() const -{ - return m_Name; -} -void Category::setName(std::string const& value) -{ - m_Name = value; - m_NameIsSet = true; -} -bool Category::nameIsSet() const -{ - return m_NameIsSet; -} -void Category::unsetName() -{ - m_NameIsSet = false; -} - - -} // namespace org::openapitools::server::model - diff --git a/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.cpp b/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.cpp index f3cc1f8076b4..e69de29bb2d1 100644 --- a/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.cpp +++ b/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.cpp @@ -1,94 +0,0 @@ -/** -* Test swagger file -* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ - - -#include "OuterType.h" -#include "Helpers.h" - -#include - -namespace org::openapitools::server::model -{ - -OuterType::OuterType() -{ - -} - -void OuterType::validate() const -{ - std::stringstream msg; - if (!validate(msg)) - { - throw org::openapitools::server::helpers::ValidationException(msg.str()); - } -} - -bool OuterType::validate(std::stringstream& msg) const -{ - return validate(msg, ""); -} - -bool OuterType::validate(std::stringstream& msg, const std::string& pathPrefix) const -{ - bool success = true; - const std::string _pathPrefix = pathPrefix.empty() ? "OuterType" : pathPrefix; - - - if (!m_Middle.validate(msg, _pathPrefix + ".middle")) { - msg << _pathPrefix << ": Middle is invalid;"; - success = false; - } - return success; -} - -bool OuterType::operator==(const OuterType& rhs) const -{ - return - - - (getMiddle() == rhs.getMiddle()) - - - ; -} - -bool OuterType::operator!=(const OuterType& rhs) const -{ - return !(*this == rhs); -} - -void to_json(nlohmann::json& j, const OuterType& o) -{ - j = nlohmann::json::object(); - j["middle"] = o.m_Middle; - -} - -void from_json(const nlohmann::json& j, OuterType& o) -{ - j.at("middle").get_to(o.m_Middle); - -} - -org::openapitools::server::model::MiddleType OuterType::getMiddle() const -{ - return m_Middle; -} -void OuterType::setMiddle(org::openapitools::server::model::MiddleType const& value) -{ - m_Middle = value; -} - - -} // namespace org::openapitools::server::model - From 2c93d4a6d00789991adaaad4135412d0a190e0ff Mon Sep 17 00:00:00 2001 From: Pavel Slabko Date: Thu, 12 Feb 2026 13:47:11 +0100 Subject: [PATCH 2/5] imptove py sdk anyOf / allOf --- .../resources/python/model_anyof.mustache | 162 ++------- .../main/resources/python/model_doc.mustache | 8 +- .../resources/python/model_generic.mustache | 329 +++--------------- .../resources/python/model_oneof.mustache | 188 ++-------- samples/client/others/c/bearerAuth/src/list.c | 200 ----------- .../apex/config/project-scratch-def.json | 8 - samples/client/petstore/bash/docs/EnumTest.md | 14 - .../model/model_with_set_propertes.h | 41 --- .../client/petstore/c/model/api_response.c | 142 -------- .../client/petstore/cpp-oatpp/model/Tag.hpp | 51 --- .../src/Org.OpenAPITools/appsettings.json | 8 - .../src/Org.OpenAPITools/appsettings.json | 8 - .../src/Org.OpenAPITools/appsettings.json | 8 - .../src/Org.OpenAPITools/appsettings.json | 8 - .../src/Org.OpenAPITools/Dockerfile | 32 -- .../src/Org.OpenAPITools/appsettings.json | 8 - .../OpenApi/TypeExtensions.cs | 61 ---- .../Org.OpenAPITools/Org.OpenAPITools.nuspec | 20 -- .../src/Org.OpenAPITools/appsettings.json | 8 - .../src/Org.OpenAPITools/Dockerfile | 32 -- .../src/Org.OpenAPITools/Dockerfile | 32 -- .../src/Org.OpenAPITools/appsettings.json | 8 - .../Org.OpenAPITools/Org.OpenAPITools.csproj | 27 -- .../src/Org.OpenAPITools/Dockerfile | 32 -- .../Org.OpenAPITools/Org.OpenAPITools.nuspec | 20 -- .../src/Org.OpenAPITools/appsettings.json | 8 - .../Properties/launchSettings.json | 30 -- .../server/petstore/cpp-oatpp/model/Tag.hpp | 51 --- .../model/Category.cpp | 144 ++++++++ .../cpp-pistache-everything/model/Order.h | 124 ------- .../model/OuterType.h | 77 ---- 31 files changed, 253 insertions(+), 1636 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/model_anyof.mustache b/modules/openapi-generator/src/main/resources/python/model_anyof.mustache index e035e4829b6f..8d1899716b69 100644 --- a/modules/openapi-generator/src/main/resources/python/model_anyof.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_anyof.mustache @@ -1,6 +1,4 @@ from __future__ import annotations -from inspect import getfullargspec -import json import pprint import re # noqa: F401 {{#vendorExtensions.x-py-other-imports}} @@ -11,167 +9,57 @@ import re # noqa: F401 {{/vendorExtensions.x-py-model-imports}} from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self -from pydantic import Field +from pydantic import Field, RootModel {{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS = [{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}] -class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): + +class {{classname}}(RootModel[Union[{{#anyOf}}{{.}}{{^-last}}, {{/-last}}{{/anyOf}}]]): """ {{{description}}}{{^description}}{{{classname}}}{{/description}} """ -{{#composedSchemas.anyOf}} - # data type: {{{dataType}}} - {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} -{{/composedSchemas.anyOf}} - if TYPE_CHECKING: - actual_instance: Optional[Union[{{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}]] = None - else: - actual_instance: Any = None - any_of_schemas: Set[str] = { {{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}} } - - model_config = { - "validate_assignment": True, - "protected_namespaces": (), - } -{{#discriminator}} + root: Union[{{#anyOf}}{{.}}{{^-last}}, {{/-last}}{{/anyOf}}{{#isNullable}}, None{{/isNullable}}] = Field( + {{#isNullable}}None{{/isNullable}}{{^isNullable}}...{{/isNullable}}{{#discriminator}}, discriminator="{{discriminatorName}}"{{/discriminator}} + ) - discriminator_value_class_map: Dict[str, str] = { -{{#children}} - '{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}},{{/-last}} -{{/children}} - } -{{/discriminator}} + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) + if name in self.__dict__: + return super().__getattribute__(name) - @field_validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - {{#isNullable}} - if v is None: - return v + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) - {{/isNullable}} - instance = {{{classname}}}.model_construct() - error_messages = [] - {{#composedSchemas.anyOf}} - # validate data type: {{{dataType}}} - {{#isContainer}} - try: - instance.{{vendorExtensions.x-py-name}} = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isContainer}} - {{^isContainer}} - {{#isPrimitiveType}} - try: - instance.{{vendorExtensions.x-py-name}} = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - if not isinstance(v, {{{dataType}}}): - error_messages.append(f"Error! Input type `{type(v)}` is not `{{{dataType}}}`") - else: - return v - - {{/isPrimitiveType}} - {{/isContainer}} - {{/composedSchemas.anyOf}} - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages)) - else: - return v + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod def from_dict(cls, obj: Dict[str, Any]) -> Self: - return cls.from_json(json.dumps(obj)) + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - {{#isNullable}} - if json_str is None: - return instance - - {{/isNullable}} - error_messages = [] - {{#composedSchemas.anyOf}} - {{#isContainer}} - # deserialize data into {{{dataType}}} - try: - # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.{{vendorExtensions.x-py-name}} - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isContainer}} - {{^isContainer}} - {{#isPrimitiveType}} - # deserialize data into {{{dataType}}} - try: - # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.{{vendorExtensions.x-py-name}} - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - # {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} - try: - instance.actual_instance = {{{dataType}}}.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{/isContainer}} - {{/composedSchemas.anyOf}} - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) + return self.model_dump_json(by_alias=True, exclude_none=True) - def to_dict(self) -> Optional[Union[Dict[str, Any], {{#anyOf}}{{.}}{{^-last}}, {{/-last}}{{/anyOf}}]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) + {{#vendorExtensions.x-py-postponed-model-imports.size}} {{#vendorExtensions.x-py-postponed-model-imports}} diff --git a/modules/openapi-generator/src/main/resources/python/model_doc.mustache b/modules/openapi-generator/src/main/resources/python/model_doc.mustache index 98d50cf8e6ea..5cc9d273dfb3 100644 --- a/modules/openapi-generator/src/main/resources/python/model_doc.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_doc.mustache @@ -19,14 +19,14 @@ from {{modelPackage}}.{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}} im # TODO update the JSON string below json = "{}" # create an instance of {{classname}} from a JSON string -{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance = {{classname}}.from_json(json) +{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance = {{classname}}.model_validate_json(json) # print the JSON string representation of the object -print({{classname}}.to_json()) +print({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance.to_dict() +{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict = {{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_instance.model_dump(by_alias=True) # create an instance of {{classname}} from a dict -{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_from_dict = {{classname}}.from_dict({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict) +{{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_from_dict = {{classname}}.model_validate({{#lambda.snakecase}}{{classname}}{{/lambda.snakecase}}_dict) ``` {{/isEnum}} {{#isEnum}} diff --git a/modules/openapi-generator/src/main/resources/python/model_generic.mustache b/modules/openapi-generator/src/main/resources/python/model_generic.mustache index 70804d448de0..42089bfa2c08 100644 --- a/modules/openapi-generator/src/main/resources/python/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_generic.mustache @@ -10,7 +10,8 @@ import json {{{.}}} {{/vendorExtensions.x-py-model-imports}} from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field {{#hasChildren}} {{#discriminator}} @@ -28,7 +29,41 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{#description}}{{{description}}}{{/description}}{{^description}}{{{classname}}}{{/description}} """ # noqa: E501 {{#vars}} + {{#isEnum}} + {{#allowableValues}} + {{^isArray}} + {{#values}} + {{#-first}} + {{#-last}} + {{! Single value enum - use Literal }} + {{name}}: Literal['{{{.}}}'] = Field( + {{#required}}...{{/required}}{{^required}}None{{/required}}, + description="{{description}}{{^description}}{{{name}}} of the {{classname}}{{/description}}", + alias="{{{baseName}}}" + ) + {{/-last}} + {{^-last}} + {{! Multiple value enum - use Literal for inline enums }} + {{name}}: {{#required}}Literal[{{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]{{/required}}{{^required}}Optional[Literal[{{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]]{{/required}} = Field( + {{#required}}...{{/required}}{{^required}}None{{/required}}, + description="{{description}}{{^description}}{{{name}}} of the {{classname}}{{/description}}" + ) + {{/-last}} + {{/-first}} + {{/values}} + {{/isArray}} + {{#isArray}} + {{! Array enum - use List[Literal] }} + {{name}}: {{#required}}List[Literal[{{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]]{{/required}}{{^required}}Optional[List[Literal[{{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]]]{{/required}} = Field( + {{#required}}...{{/required}}{{^required}}None{{/required}}, + description="{{description}}{{^description}}{{{name}}} of the {{classname}}{{/description}}" + ) + {{/isArray}} + {{/allowableValues}} + {{/isEnum}} + {{^isEnum}} {{name}}: {{{vendorExtensions.x-py-typing}}} + {{/isEnum}} {{/vars}} {{#isAdditionalPropertiesTrue}} additional_properties: Dict[str, Any] = {} @@ -76,18 +111,18 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{#isContainer}} {{#isArray}} for i in value: - if i not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): - raise ValueError("each list item must be one of ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") + if i not in set([{{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): + raise ValueError("each list item must be one of ({{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") {{/isArray}} {{#isMap}} for i in value.values(): - if i not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): - raise ValueError("dict values must be one of enum values ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") + if i not in set([{{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): + raise ValueError("dict values must be one of enum values ({{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") {{/isMap}} {{/isContainer}} {{^isContainer}} - if value not in set([{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): - raise ValueError("must be one of enum values ({{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") + if value not in set([{{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]): + raise ValueError("must be one of enum values ({{#allowableValues}}{{#enumVars}}{{#isString}}{{{value}}}{{/isString}}{{^isString}}{{{value}}}{{/isString}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}})") {{/isContainer}} return value {{/isEnum}} @@ -121,278 +156,28 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{/discriminator}} {{/hasChildren}} - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - - @classmethod - def from_json(cls, json_str: str) -> Optional[{{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#mappedModels}}{{{modelName}}}{{^-last}}, {{/-last}}{{/mappedModels}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}]: - """Create an instance of {{{classname}}} from a JSON string""" - return cls.from_dict(json.loads(json_str)) - - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - {{#vendorExtensions.x-py-readonly}} - * OpenAPI `readOnly` fields are excluded. - {{/vendorExtensions.x-py-readonly}} - {{#isAdditionalPropertiesTrue}} - * Fields in `self.additional_properties` are added to the output dict. - {{/isAdditionalPropertiesTrue}} - """ - excluded_fields: Set[str] = set([ - {{#vendorExtensions.x-py-readonly}} - "{{{.}}}", - {{/vendorExtensions.x-py-readonly}} - {{#isAdditionalPropertiesTrue}} - "additional_properties", - {{/isAdditionalPropertiesTrue}} - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - {{#allVars}} - {{#isContainer}} - {{#isArray}} - {{#items.isArray}} - {{^items.items.isPrimitiveType}} - # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list of list) - _items = [] - if self.{{{name}}}: - for _item_{{{name}}} in self.{{{name}}}: - if _item_{{{name}}}: - _items.append( - [_inner_item.to_dict() for _inner_item in _item_{{{name}}} if _inner_item is not None] - ) - _dict['{{{baseName}}}'] = _items - {{/items.items.isPrimitiveType}} - {{/items.isArray}} - {{^items.isArray}} - {{^items.isPrimitiveType}} - {{^items.isEnumOrRef}} - # override the default output from pydantic by calling `to_dict()` of each item in {{{name}}} (list) - _items = [] - if self.{{{name}}}: - for _item_{{{name}}} in self.{{{name}}}: - if _item_{{{name}}}: - _items.append(_item_{{{name}}}.to_dict()) - _dict['{{{baseName}}}'] = _items - {{/items.isEnumOrRef}} - {{/items.isPrimitiveType}} - {{/items.isArray}} - {{/isArray}} - {{#isMap}} - {{#items.isArray}} - {{^items.items.isPrimitiveType}} - # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict of array) - _field_dict_of_array = {} - if self.{{{name}}}: - for _key_{{{name}}} in self.{{{name}}}: - if self.{{{name}}}[_key_{{{name}}}] is not None: - _field_dict_of_array[_key_{{{name}}}] = [ - _item.to_dict() for _item in self.{{{name}}}[_key_{{{name}}}] - ] - _dict['{{{baseName}}}'] = _field_dict_of_array - {{/items.items.isPrimitiveType}} - {{/items.isArray}} - {{^items.isArray}} - {{^items.isPrimitiveType}} - {{^items.isEnumOrRef}} - # override the default output from pydantic by calling `to_dict()` of each value in {{{name}}} (dict) - _field_dict = {} - if self.{{{name}}}: - for _key_{{{name}}} in self.{{{name}}}: - if self.{{{name}}}[_key_{{{name}}}]: - _field_dict[_key_{{{name}}}] = self.{{{name}}}[_key_{{{name}}}].to_dict() - _dict['{{{baseName}}}'] = _field_dict - {{/items.isEnumOrRef}} - {{/items.isPrimitiveType}} - {{/items.isArray}} - {{/isMap}} - {{/isContainer}} - {{^isContainer}} - {{^isPrimitiveType}} - {{^isEnumOrRef}} - # override the default output from pydantic by calling `to_dict()` of {{{name}}} - if self.{{{name}}}: - _dict['{{{baseName}}}'] = self.{{{name}}}.to_dict() - {{/isEnumOrRef}} - {{/isPrimitiveType}} - {{/isContainer}} - {{/allVars}} - {{#isAdditionalPropertiesTrue}} - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - {{/isAdditionalPropertiesTrue}} - {{#allVars}} - {{#isNullable}} - # set to None if {{{name}}} (nullable) is None - # and model_fields_set contains the field - if self.{{name}} is None and "{{{name}}}" in self.model_fields_set: - _dict['{{{baseName}}}'] = None - - {{/isNullable}} - {{/allVars}} - return _dict - - {{#hasChildren}} @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[{{#discriminator}}Union[{{#mappedModels}}{{{modelName}}}{{^-last}}, {{/-last}}{{/mappedModels}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}]: - """Create an instance of {{{classname}}} from a dict""" - {{#discriminator}} - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - {{#mappedModels}} - if object_type == '{{{modelName}}}': - return import_module("{{packageName}}.models.{{model.classFilename}}").{{modelName}}.from_dict(obj) - {{/mappedModels}} + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - raise ValueError("{{{classname}}} failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) - {{/discriminator}} - {{/hasChildren}} - {{^hasChildren}} @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of {{{classname}}} from a dict""" - if obj is None: - return None + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - if not isinstance(obj, dict): - return cls.model_validate(obj) + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - {{#disallowAdditionalPropertiesIfNotPresent}} - {{^isAdditionalPropertiesTrue}} - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in {{classname}}) in the input: " + _key) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - {{/isAdditionalPropertiesTrue}} - {{/disallowAdditionalPropertiesIfNotPresent}} - _obj = cls.model_validate({ - {{#allVars}} - {{#isContainer}} - {{#isArray}} - {{#items.isArray}} - {{#items.items.isPrimitiveType}} - "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/items.items.isPrimitiveType}} - {{^items.items.isPrimitiveType}} - "{{{baseName}}}": [ - [{{{items.items.dataType}}}.from_dict(_inner_item) for _inner_item in _item] - for _item in obj["{{{baseName}}}"] - ] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} - {{/items.items.isPrimitiveType}} - {{/items.isArray}} - {{^items.isArray}} - {{^items.isPrimitiveType}} - {{#items.isEnumOrRef}} - "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/items.isEnumOrRef}} - {{^items.isEnumOrRef}} - "{{{baseName}}}": [{{{items.dataType}}}.from_dict(_item) for _item in obj["{{{baseName}}}"]] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} - {{/items.isEnumOrRef}} - {{/items.isPrimitiveType}} - {{#items.isPrimitiveType}} - "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/items.isPrimitiveType}} - {{/items.isArray}} - {{/isArray}} - {{#isMap}} - {{^items.isPrimitiveType}} - {{^items.isEnumOrRef}} - {{#items.isContainer}} - {{#items.isMap}} - "{{{baseName}}}": dict( - (_k, dict( - (_ik, {{{items.items.dataType}}}.from_dict(_iv)) - for _ik, _iv in _v.items() - ) - if _v is not None - else None - ) - for _k, _v in obj.get("{{{baseName}}}").items() - ) - if obj.get("{{{baseName}}}") is not None - else None{{^-last}},{{/-last}} - {{/items.isMap}} - {{#items.isArray}} - "{{{baseName}}}": dict( - (_k, - [{{{items.items.dataType}}}.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("{{{baseName}}}", {}).items() - ){{^-last}},{{/-last}} - {{/items.isArray}} - {{/items.isContainer}} - {{^items.isContainer}} - "{{{baseName}}}": dict( - (_k, {{{items.dataType}}}.from_dict(_v)) - for _k, _v in obj["{{{baseName}}}"].items() - ) - if obj.get("{{{baseName}}}") is not None - else None{{^-last}},{{/-last}} - {{/items.isContainer}} - {{/items.isEnumOrRef}} - {{#items.isEnumOrRef}} - "{{{baseName}}}": dict((_k, _v) for _k, _v in obj.get("{{{baseName}}}").items()) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} - {{/items.isEnumOrRef}} - {{/items.isPrimitiveType}} - {{#items.isPrimitiveType}} - "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/items.isPrimitiveType}} - {{/isMap}} - {{/isContainer}} - {{^isContainer}} - {{^isPrimitiveType}} - {{^isEnumOrRef}} - "{{{baseName}}}": {{{dataType}}}.from_dict(obj["{{{baseName}}}"]) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} - {{/isEnumOrRef}} - {{#isEnumOrRef}} - "{{{baseName}}}": obj.get("{{{baseName}}}"){{#defaultValue}} if obj.get("{{baseName}}") is not None else {{{defaultValue}}}{{/defaultValue}}{{^-last}},{{/-last}} - {{/isEnumOrRef}} - {{/isPrimitiveType}} - {{#isPrimitiveType}} - {{#defaultValue}} - "{{{baseName}}}": obj.get("{{{baseName}}}") if obj.get("{{{baseName}}}") is not None else {{{defaultValue}}}{{^-last}},{{/-last}} - {{/defaultValue}} - {{^defaultValue}} - "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} - {{/defaultValue}} - {{/isPrimitiveType}} - {{/isContainer}} - {{/allVars}} - }) - {{#isAdditionalPropertiesTrue}} - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - {{/isAdditionalPropertiesTrue}} - return _obj - {{/hasChildren}} {{#vendorExtensions.x-py-postponed-model-imports.size}} {{#vendorExtensions.x-py-postponed-model-imports}} diff --git a/modules/openapi-generator/src/main/resources/python/model_oneof.mustache b/modules/openapi-generator/src/main/resources/python/model_oneof.mustache index 07a4d93f9ddf..03f0766ea3e0 100644 --- a/modules/openapi-generator/src/main/resources/python/model_oneof.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_oneof.mustache @@ -7,198 +7,56 @@ import pprint {{#vendorExtensions.x-py-model-imports}} {{{.}}} {{/vendorExtensions.x-py-model-imports}} -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self {{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS = [{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}] -class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): +class {{classname}}(RootModel[Union[{{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}]]): """ {{{description}}}{{^description}}{{{classname}}}{{/description}} """ -{{#composedSchemas.oneOf}} - # data type: {{{dataType}}} - {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} -{{/composedSchemas.oneOf}} - actual_instance: Optional[Union[{{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}]] = None - one_of_schemas: Set[str] = { {{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}} } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[{{#oneOf}}{{.}}{{^-last}}, {{/-last}}{{/oneOf}}{{#isNullable}}, None{{/isNullable}}] = Field( + {{#isNullable}}None{{/isNullable}}{{^isNullable}}...{{/isNullable}}{{#discriminator}}, discriminator="{{discriminatorName}}"{{/discriminator}} ) -{{#discriminator}} - - discriminator_value_class_map: Dict[str, str] = { -{{#children}} - '{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}},{{/-last}} -{{/children}} - } -{{/discriminator}} + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) + if name in self.__dict__: + return super().__getattribute__(name) - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - {{#isNullable}} - if v is None: - return v + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) - {{/isNullable}} - instance = {{{classname}}}.model_construct() - error_messages = [] - match = 0 - {{#composedSchemas.oneOf}} - # validate data type: {{{dataType}}} - {{#isContainer}} - try: - instance.{{vendorExtensions.x-py-name}} = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isContainer}} - {{^isContainer}} - {{#isPrimitiveType}} - try: - instance.{{vendorExtensions.x-py-name}} = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - if not isinstance(v, {{{dataType}}}): - error_messages.append(f"Error! Input type `{type(v)}` is not `{{{dataType}}}`") - else: - match += 1 - {{/isPrimitiveType}} - {{/isContainer}} - {{/composedSchemas.oneOf}} - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) - else: - return v + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - {{#isNullable}} - def from_json(cls, json_str: Optional[str]) -> Self: - {{/isNullable}} - {{^isNullable}} def from_json(cls, json_str: str) -> Self: - {{/isNullable}} """Returns the object represented by the json string""" - instance = cls.model_construct() - {{#isNullable}} - if json_str is None: - return instance - - {{/isNullable}} - error_messages = [] - match = 0 - - {{#useOneOfDiscriminatorLookup}} - {{#discriminator}} - {{#mappedModels}} - {{#-first}} - # use oneOf discriminator to lookup the data type - _data_type = json.loads(json_str).get("{{{propertyBaseName}}}") - if not _data_type: - raise ValueError("Failed to lookup data type from the field `{{{propertyBaseName}}}` in the input.") - - {{/-first}} - # check if data type is `{{{modelName}}}` - if _data_type == "{{{mappingName}}}": - instance.actual_instance = {{{modelName}}}.from_json(json_str) - return instance - - {{/mappedModels}} - {{/discriminator}} - {{/useOneOfDiscriminatorLookup}} - {{#composedSchemas.oneOf}} - {{#isContainer}} - # deserialize data into {{{dataType}}} - try: - # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.{{vendorExtensions.x-py-name}} - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isContainer}} - {{^isContainer}} - {{#isPrimitiveType}} - # deserialize data into {{{dataType}}} - try: - # validation - instance.{{vendorExtensions.x-py-name}} = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.{{vendorExtensions.x-py-name}} - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{^isPrimitiveType}} - # deserialize data into {{{dataType}}} - try: - instance.actual_instance = {{{dataType}}}.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - {{/isPrimitiveType}} - {{/isContainer}} - {{/composedSchemas.oneOf}} - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into {{{classname}}} with oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) {{#vendorExtensions.x-py-postponed-model-imports.size}} {{#vendorExtensions.x-py-postponed-model-imports}} diff --git a/samples/client/others/c/bearerAuth/src/list.c b/samples/client/others/c/bearerAuth/src/list.c index 7053ff122dfc..e69de29bb2d1 100644 --- a/samples/client/others/c/bearerAuth/src/list.c +++ b/samples/client/others/c/bearerAuth/src/list.c @@ -1,200 +0,0 @@ -#include -#include -#include -#include - -#include "../include/list.h" -static listEntry_t *listEntry_create(void *data) { - listEntry_t *createdListEntry = malloc(sizeof(listEntry_t)); - if(createdListEntry == NULL) { - // TODO Malloc Failure - return NULL; - } - createdListEntry->data = data; - - return createdListEntry; -} - -void listEntry_free(listEntry_t *listEntry, void *additionalData) { - free(listEntry); -} - -void listEntry_printAsInt(listEntry_t *listEntry, void *additionalData) { - printf("%i\n", *(int *)listEntry->data); -} - -list_t *list_createList() { - list_t *createdList = malloc(sizeof(list_t)); - if(createdList == NULL) { - // TODO Malloc Failure - return NULL; - } - createdList->firstEntry = NULL; - createdList->lastEntry = NULL; - createdList->count = 0; - - return createdList; -} - -void list_iterateThroughListForward(list_t *list, - void (*operationToPerform)( - listEntry_t *, - void *callbackFunctionUsedData), - void *additionalDataNeededForCallbackFunction) -{ - listEntry_t *currentListEntry = list->firstEntry; - listEntry_t *nextListEntry; - - if(currentListEntry == NULL) { - return; - } - - nextListEntry = currentListEntry->nextListEntry; - - operationToPerform(currentListEntry, - additionalDataNeededForCallbackFunction); - currentListEntry = nextListEntry; - - while(currentListEntry != NULL) { - nextListEntry = currentListEntry->nextListEntry; - operationToPerform(currentListEntry, - additionalDataNeededForCallbackFunction); - currentListEntry = nextListEntry; - } -} - -void list_iterateThroughListBackward(list_t *list, - void (*operationToPerform)( - listEntry_t *, - void *callbackFunctionUsedData), - void *additionalDataNeededForCallbackFunction) -{ - listEntry_t *currentListEntry = list->lastEntry; - listEntry_t *nextListEntry = currentListEntry->prevListEntry; - - if(currentListEntry == NULL) { - return; - } - - operationToPerform(currentListEntry, - additionalDataNeededForCallbackFunction); - currentListEntry = nextListEntry; - - while(currentListEntry != NULL) { - nextListEntry = currentListEntry->prevListEntry; - operationToPerform(currentListEntry, - additionalDataNeededForCallbackFunction); - currentListEntry = nextListEntry; - } -} - -void list_freeList(list_t *list) { - if(list){ - list_iterateThroughListForward(list, listEntry_free, NULL); - free(list); - } -} - -void list_addElement(list_t *list, void *dataToAddInList) { - listEntry_t *newListEntry = listEntry_create(dataToAddInList); - if(newListEntry == NULL) { - // TODO Malloc Failure - return; - } - if(list->firstEntry == NULL) { - list->firstEntry = newListEntry; - list->lastEntry = newListEntry; - - newListEntry->prevListEntry = NULL; - newListEntry->nextListEntry = NULL; - - list->count++; - - return; - } - - list->lastEntry->nextListEntry = newListEntry; - newListEntry->prevListEntry = list->lastEntry; - newListEntry->nextListEntry = NULL; - list->lastEntry = newListEntry; - - list->count++; -} - -void list_removeElement(list_t *list, listEntry_t *elementToRemove) { - listEntry_t *elementBeforeElementToRemove = - elementToRemove->prevListEntry; - listEntry_t *elementAfterElementToRemove = - elementToRemove->nextListEntry; - - if(elementBeforeElementToRemove != NULL) { - elementBeforeElementToRemove->nextListEntry = - elementAfterElementToRemove; - } else { - list->firstEntry = elementAfterElementToRemove; - } - - if(elementAfterElementToRemove != NULL) { - elementAfterElementToRemove->prevListEntry = - elementBeforeElementToRemove; - } else { - list->lastEntry = elementBeforeElementToRemove; - } - - listEntry_free(elementToRemove, NULL); - - list->count--; -} - -listEntry_t *list_getElementAt(list_t *list, long indexOfElement) { - listEntry_t *currentListEntry; - - if((list->count / 2) > indexOfElement) { - currentListEntry = list->firstEntry; - - for(int i = 0; i < indexOfElement; i++) { - currentListEntry = currentListEntry->nextListEntry; - } - - return currentListEntry; - } else { - currentListEntry = list->lastEntry; - - for(int i = 1; i < (list->count - indexOfElement); i++) { - currentListEntry = currentListEntry->prevListEntry; - } - - return currentListEntry; - } -} - -char* findStrInStrList(list_t *strList, const char *str) -{ - if (!strList || !str) { - return NULL; - } - - listEntry_t* listEntry = NULL; - list_ForEach(listEntry, strList) { - if (strstr(listEntry->data, str) != NULL) { - return listEntry->data; - } - } - - return NULL; -} - -void clear_and_free_string_list(list_t *list) -{ - if (!list) { - return; - } - - listEntry_t *listEntry = NULL; - list_ForEach(listEntry, list) { - char *list_item = listEntry->data; - free(list_item); - list_item = NULL; - } - list_freeList(list); -} diff --git a/samples/client/petstore/apex/config/project-scratch-def.json b/samples/client/petstore/apex/config/project-scratch-def.json index 36aace552669..e69de29bb2d1 100644 --- a/samples/client/petstore/apex/config/project-scratch-def.json +++ b/samples/client/petstore/apex/config/project-scratch-def.json @@ -1,8 +0,0 @@ -{ - "orgName": "muenzpraeger - René Winkelmeyer", - "edition": "Developer", - "orgPreferences": { - "enabled": ["S1DesktopEnabled"], - "disabled": ["S1EncryptedStoragePref2"] - } -} diff --git a/samples/client/petstore/bash/docs/EnumTest.md b/samples/client/petstore/bash/docs/EnumTest.md index 30b30efa7307..e69de29bb2d1 100644 --- a/samples/client/petstore/bash/docs/EnumTest.md +++ b/samples/client/petstore/bash/docs/EnumTest.md @@ -1,14 +0,0 @@ -# Enum_Test - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**enumUnderscorestring** | **string** | | [optional] [default to null] -**enumUnderscorestringUnderscorerequired** | **string** | | [default to null] -**enumUnderscoreinteger** | **integer** | | [optional] [default to null] -**enumUnderscorenumber** | **float** | | [optional] [default to null] -**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] [default to null] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/client/petstore/c-useJsonUnformatted/model/model_with_set_propertes.h b/samples/client/petstore/c-useJsonUnformatted/model/model_with_set_propertes.h index aa82893b94bb..e69de29bb2d1 100644 --- a/samples/client/petstore/c-useJsonUnformatted/model/model_with_set_propertes.h +++ b/samples/client/petstore/c-useJsonUnformatted/model/model_with_set_propertes.h @@ -1,41 +0,0 @@ -/* - * model_with_set_propertes.h - * - * to test set properties - */ - -#ifndef _model_with_set_propertes_H_ -#define _model_with_set_propertes_H_ - -#include -#include "../external/cJSON.h" -#include "../include/list.h" -#include "../include/keyValuePair.h" -#include "../include/binary.h" - -typedef struct model_with_set_propertes_t model_with_set_propertes_t; - -#include "tag.h" - - - -typedef struct model_with_set_propertes_t { - list_t *tag_set; //nonprimitive container - list_t *string_set; //primitive container - - int _library_owned; // Is the library responsible for freeing this object? -} model_with_set_propertes_t; - -__attribute__((deprecated)) model_with_set_propertes_t *model_with_set_propertes_create( - list_t *tag_set, - list_t *string_set -); - -void model_with_set_propertes_free(model_with_set_propertes_t *model_with_set_propertes); - -model_with_set_propertes_t *model_with_set_propertes_parseFromJSON(cJSON *model_with_set_propertesJSON); - -cJSON *model_with_set_propertes_convertToJSON(model_with_set_propertes_t *model_with_set_propertes); - -#endif /* _model_with_set_propertes_H_ */ - diff --git a/samples/client/petstore/c/model/api_response.c b/samples/client/petstore/c/model/api_response.c index d0169c84f5b2..e69de29bb2d1 100644 --- a/samples/client/petstore/c/model/api_response.c +++ b/samples/client/petstore/c/model/api_response.c @@ -1,142 +0,0 @@ -#include -#include -#include -#include "api_response.h" - - - -static api_response_t *api_response_create_internal( - int code, - char *type, - char *message - ) { - api_response_t *api_response_local_var = malloc(sizeof(api_response_t)); - if (!api_response_local_var) { - return NULL; - } - api_response_local_var->code = code; - api_response_local_var->type = type; - api_response_local_var->message = message; - - api_response_local_var->_library_owned = 1; - return api_response_local_var; -} - -__attribute__((deprecated)) api_response_t *api_response_create( - int code, - char *type, - char *message - ) { - return api_response_create_internal ( - code, - type, - message - ); -} - -void api_response_free(api_response_t *api_response) { - if(NULL == api_response){ - return ; - } - if(api_response->_library_owned != 1){ - fprintf(stderr, "WARNING: %s() does NOT free objects allocated by the user\n", "api_response_free"); - return ; - } - listEntry_t *listEntry; - if (api_response->type) { - free(api_response->type); - api_response->type = NULL; - } - if (api_response->message) { - free(api_response->message); - api_response->message = NULL; - } - free(api_response); -} - -cJSON *api_response_convertToJSON(api_response_t *api_response) { - cJSON *item = cJSON_CreateObject(); - - // api_response->code - if(api_response->code) { - if(cJSON_AddNumberToObject(item, "code", api_response->code) == NULL) { - goto fail; //Numeric - } - } - - - // api_response->type - if(api_response->type) { - if(cJSON_AddStringToObject(item, "type", api_response->type) == NULL) { - goto fail; //String - } - } - - - // api_response->message - if(api_response->message) { - if(cJSON_AddStringToObject(item, "message", api_response->message) == NULL) { - goto fail; //String - } - } - - return item; -fail: - if (item) { - cJSON_Delete(item); - } - return NULL; -} - -api_response_t *api_response_parseFromJSON(cJSON *api_responseJSON){ - - api_response_t *api_response_local_var = NULL; - - // api_response->code - cJSON *code = cJSON_GetObjectItemCaseSensitive(api_responseJSON, "code"); - if (cJSON_IsNull(code)) { - code = NULL; - } - if (code) { - if(!cJSON_IsNumber(code)) - { - goto end; //Numeric - } - } - - // api_response->type - cJSON *type = cJSON_GetObjectItemCaseSensitive(api_responseJSON, "type"); - if (cJSON_IsNull(type)) { - type = NULL; - } - if (type) { - if(!cJSON_IsString(type) && !cJSON_IsNull(type)) - { - goto end; //String - } - } - - // api_response->message - cJSON *message = cJSON_GetObjectItemCaseSensitive(api_responseJSON, "message"); - if (cJSON_IsNull(message)) { - message = NULL; - } - if (message) { - if(!cJSON_IsString(message) && !cJSON_IsNull(message)) - { - goto end; //String - } - } - - - api_response_local_var = api_response_create_internal ( - code ? code->valuedouble : 0, - type && !cJSON_IsNull(type) ? strdup(type->valuestring) : NULL, - message && !cJSON_IsNull(message) ? strdup(message->valuestring) : NULL - ); - - return api_response_local_var; -end: - return NULL; - -} diff --git a/samples/client/petstore/cpp-oatpp/model/Tag.hpp b/samples/client/petstore/cpp-oatpp/model/Tag.hpp index befd6854d51e..e69de29bb2d1 100644 --- a/samples/client/petstore/cpp-oatpp/model/Tag.hpp +++ b/samples/client/petstore/cpp-oatpp/model/Tag.hpp @@ -1,51 +0,0 @@ -/** -* OpenAPI Petstore -* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ -/* - * Tag.h - * - * A tag for a pet - */ - -#ifndef Tag_H_ -#define Tag_H_ - - -#include "oatpp/core/macro/codegen.hpp" -#include "oatpp/core/Types.hpp" - -namespace org::openapitools::client::model -{ - -/* Begin DTO code-generation */ -#include OATPP_CODEGEN_BEGIN(DTO) - -/** - * Message Data-Transfer-Object - */ -class Tag : public oatpp::DTO { - - DTO_INIT(Tag, DTO /* Extends */) - - DTO_FIELD(oatpp::Int64, id); - DTO_FIELD(oatpp::Boolean, idIsSet); - DTO_FIELD(oatpp::String, name); - DTO_FIELD(oatpp::Boolean, nameIsSet); - -}; - -/* End DTO code-generation */ -#include OATPP_CODEGEN_END(DTO) - - -} // namespace org::openapitools::client::model - -#endif /* Tag_H_ */ diff --git a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/appsettings.json index def9159a7d94..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/appsettings.json @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/appsettings.json index def9159a7d94..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/appsettings.json @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/appsettings.json index def9159a7d94..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/appsettings.json @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/appsettings.json index def9159a7d94..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/appsettings.json @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile index 7184e1ece4d0..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile +++ b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile @@ -1,32 +0,0 @@ -#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. - -# Container we use for final publish -FROM mcr.microsoft.com/dotnet/core/aspnet:6.0-buster-slim AS base -WORKDIR /app -EXPOSE 80 -EXPOSE 443 - -# Build container -FROM mcr.microsoft.com/dotnet/core/sdk:6.0-buster AS build - -# Copy the code into the container -WORKDIR /src -COPY ["src/Org.OpenAPITools/Org.OpenAPITools.csproj", "Org.OpenAPITools/"] - -# NuGet restore -RUN dotnet restore "Org.OpenAPITools/Org.OpenAPITools.csproj" -COPY ["src/Org.OpenAPITools/", "Org.OpenAPITools/"] - -# Build the API -WORKDIR "Org.OpenAPITools" -RUN dotnet build "Org.OpenAPITools.csproj" -c Release -o /app/build - -# Publish it -FROM build AS publish -RUN dotnet publish "Org.OpenAPITools.csproj" -c Release -o /app/publish - -# Make the final image for publishing -FROM base AS final -WORKDIR /app -COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "Org.OpenAPITools.dll"] diff --git a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/appsettings.json index def9159a7d94..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/appsettings.json @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs index 122f58cabe4a..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs @@ -1,61 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System; -using System.Linq; -using System.Text; - -namespace Org.OpenAPITools.OpenApi -{ - /// - /// Replacement utilities from Swashbuckle.AspNetCore.SwaggerGen which are not in 5.x - /// - public static class TypeExtensions - { - /// - /// Produce a friendly name for the type which is unique. - /// - /// - /// - public static string FriendlyId(this Type type, bool fullyQualified = false) - { - var typeName = fullyQualified - ? type.FullNameSansTypeParameters().Replace("+", ".") - : type.Name; - - if (type.IsGenericType) - { - var genericArgumentIds = type.GetGenericArguments() - .Select(t => t.FriendlyId(fullyQualified)) - .ToArray(); - - return new StringBuilder(typeName) - .Replace($"`{genericArgumentIds.Count()}", string.Empty) - .Append($"[{string.Join(",", genericArgumentIds).TrimEnd(',')}]") - .ToString(); - } - - return typeName; - } - - /// - /// Determine the fully qualified type name without type parameters. - /// - /// - public static string FullNameSansTypeParameters(this Type type) - { - var fullName = type.FullName; - if (string.IsNullOrEmpty(fullName)) - fullName = type.Name; - var chopIndex = fullName.IndexOf("[[", StringComparison.Ordinal); - return (chopIndex == -1) ? fullName : fullName.Substring(0, chopIndex); - } - } -} \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec index b1d83a359618..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec +++ b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec @@ -1,20 +0,0 @@ - - - - $id$ - 1.0.0 - OpenAPI Library - OpenAPI - OpenAPI - https://www.apache.org/licenses/LICENSE-2.0.html - - false - A library generated from a OpenAPI doc - Summary of changes made in this release of the package. - No Copyright - Org.OpenAPITools - - diff --git a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/appsettings.json index def9159a7d94..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/appsettings.json @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Dockerfile b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Dockerfile index c24f45dbc5a4..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Dockerfile +++ b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Dockerfile @@ -1,32 +0,0 @@ -#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. - -# Container we use for final publish -FROM mcr.microsoft.com/dotnet/core/aspnet:8.0-buster-slim AS base -WORKDIR /app -EXPOSE 80 -EXPOSE 443 - -# Build container -FROM mcr.microsoft.com/dotnet/core/sdk:8.0-buster AS build - -# Copy the code into the container -WORKDIR /src -COPY ["src/Org.OpenAPITools/Org.OpenAPITools.csproj", "Org.OpenAPITools/"] - -# NuGet restore -RUN dotnet restore "Org.OpenAPITools/Org.OpenAPITools.csproj" -COPY ["src/Org.OpenAPITools/", "Org.OpenAPITools/"] - -# Build the API -WORKDIR "Org.OpenAPITools" -RUN dotnet build "Org.OpenAPITools.csproj" -c Release -o /app/build - -# Publish it -FROM build AS publish -RUN dotnet publish "Org.OpenAPITools.csproj" -c Release -o /app/publish - -# Make the final image for publishing -FROM base AS final -WORKDIR /app -COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "Org.OpenAPITools.dll"] diff --git a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile index c24f45dbc5a4..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile +++ b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile @@ -1,32 +0,0 @@ -#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. - -# Container we use for final publish -FROM mcr.microsoft.com/dotnet/core/aspnet:8.0-buster-slim AS base -WORKDIR /app -EXPOSE 80 -EXPOSE 443 - -# Build container -FROM mcr.microsoft.com/dotnet/core/sdk:8.0-buster AS build - -# Copy the code into the container -WORKDIR /src -COPY ["src/Org.OpenAPITools/Org.OpenAPITools.csproj", "Org.OpenAPITools/"] - -# NuGet restore -RUN dotnet restore "Org.OpenAPITools/Org.OpenAPITools.csproj" -COPY ["src/Org.OpenAPITools/", "Org.OpenAPITools/"] - -# Build the API -WORKDIR "Org.OpenAPITools" -RUN dotnet build "Org.OpenAPITools.csproj" -c Release -o /app/build - -# Publish it -FROM build AS publish -RUN dotnet publish "Org.OpenAPITools.csproj" -c Release -o /app/publish - -# Make the final image for publishing -FROM base AS final -WORKDIR /app -COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "Org.OpenAPITools.dll"] diff --git a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/appsettings.json index def9159a7d94..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/appsettings.json @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 99b5e849d995..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -1,27 +0,0 @@ - - - A library generated from a OpenAPI doc - No Copyright - OpenAPI - net8.0 - true - true - 1.0.0 - Org.OpenAPITools - Org.OpenAPITools - cb87e868-8646-48ef-9bb6-344b537d0d37 - Linux - ..\.. - - - - - - - - - - - - - diff --git a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Dockerfile b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Dockerfile index c24f45dbc5a4..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Dockerfile +++ b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Dockerfile @@ -1,32 +0,0 @@ -#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. - -# Container we use for final publish -FROM mcr.microsoft.com/dotnet/core/aspnet:8.0-buster-slim AS base -WORKDIR /app -EXPOSE 80 -EXPOSE 443 - -# Build container -FROM mcr.microsoft.com/dotnet/core/sdk:8.0-buster AS build - -# Copy the code into the container -WORKDIR /src -COPY ["src/Org.OpenAPITools/Org.OpenAPITools.csproj", "Org.OpenAPITools/"] - -# NuGet restore -RUN dotnet restore "Org.OpenAPITools/Org.OpenAPITools.csproj" -COPY ["src/Org.OpenAPITools/", "Org.OpenAPITools/"] - -# Build the API -WORKDIR "Org.OpenAPITools" -RUN dotnet build "Org.OpenAPITools.csproj" -c Release -o /app/build - -# Publish it -FROM build AS publish -RUN dotnet publish "Org.OpenAPITools.csproj" -c Release -o /app/publish - -# Make the final image for publishing -FROM base AS final -WORKDIR /app -COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "Org.OpenAPITools.dll"] diff --git a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec index b1d83a359618..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec +++ b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec @@ -1,20 +0,0 @@ - - - - $id$ - 1.0.0 - OpenAPI Library - OpenAPI - OpenAPI - https://www.apache.org/licenses/LICENSE-2.0.html - - false - A library generated from a OpenAPI doc - Summary of changes made in this release of the package. - No Copyright - Org.OpenAPITools - - diff --git a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/appsettings.json index def9159a7d94..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/appsettings.json @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" -} diff --git a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Properties/launchSettings.json b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Properties/launchSettings.json index 1b527df2c2b3..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Properties/launchSettings.json +++ b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Properties/launchSettings.json @@ -1,30 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:61788", - "sslPort": 44301 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "api/values", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "WebApplication1": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "api/values", - "applicationUrl": "https://localhost:5001;http://localhost:5000", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} \ No newline at end of file diff --git a/samples/server/petstore/cpp-oatpp/model/Tag.hpp b/samples/server/petstore/cpp-oatpp/model/Tag.hpp index f7941e8e3911..e69de29bb2d1 100644 --- a/samples/server/petstore/cpp-oatpp/model/Tag.hpp +++ b/samples/server/petstore/cpp-oatpp/model/Tag.hpp @@ -1,51 +0,0 @@ -/** -* OpenAPI Petstore -* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ -/* - * Tag.h - * - * A tag for a pet - */ - -#ifndef Tag_H_ -#define Tag_H_ - - -#include "oatpp/core/macro/codegen.hpp" -#include "oatpp/core/Types.hpp" - -namespace org::openapitools::server::model -{ - -/* Begin DTO code-generation */ -#include OATPP_CODEGEN_BEGIN(DTO) - -/** - * Message Data-Transfer-Object - */ -class Tag : public oatpp::DTO { - - DTO_INIT(Tag, DTO /* Extends */) - - DTO_FIELD(oatpp::Int64, id); - DTO_FIELD(oatpp::Boolean, idIsSet); - DTO_FIELD(oatpp::String, name); - DTO_FIELD(oatpp::Boolean, nameIsSet); - -}; - -/* End DTO code-generation */ -#include OATPP_CODEGEN_END(DTO) - - -} // namespace org::openapitools::server::model - -#endif /* Tag_H_ */ diff --git a/samples/server/petstore/cpp-pistache-everything/model/Category.cpp b/samples/server/petstore/cpp-pistache-everything/model/Category.cpp index e69de29bb2d1..bd76b4cd6630 100644 --- a/samples/server/petstore/cpp-pistache-everything/model/Category.cpp +++ b/samples/server/petstore/cpp-pistache-everything/model/Category.cpp @@ -0,0 +1,144 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + + +#include "Category.h" +#include "Helpers.h" + +#include + +namespace org::openapitools::server::model +{ + +Category::Category() +{ + m_Id = 0L; + m_IdIsSet = false; + m_Name = ""; + m_NameIsSet = false; + +} + +void Category::validate() const +{ + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } +} + +bool Category::validate(std::stringstream& msg) const +{ + return validate(msg, ""); +} + +bool Category::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Category" : pathPrefix; + + + if (nameIsSet()) + { + const std::string& value = m_Name; + const std::string currentValuePath = _pathPrefix + ".name"; + + + + } + + return success; +} + +bool Category::operator==(const Category& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!nameIsSet() && !rhs.nameIsSet()) || (nameIsSet() && rhs.nameIsSet() && getName() == rhs.getName())) + + ; +} + +bool Category::operator!=(const Category& rhs) const +{ + return !(*this == rhs); +} + +void to_json(nlohmann::json& j, const Category& o) +{ + j = nlohmann::json::object(); + if(o.idIsSet()) + j["id"] = o.m_Id; + if(o.nameIsSet()) + j["name"] = o.m_Name; + +} + +void from_json(const nlohmann::json& j, Category& o) +{ + if(j.find("id") != j.end()) + { + j.at("id").get_to(o.m_Id); + o.m_IdIsSet = true; + } + if(j.find("name") != j.end()) + { + j.at("name").get_to(o.m_Name); + o.m_NameIsSet = true; + } + +} + +int64_t Category::getId() const +{ + return m_Id; +} +void Category::setId(int64_t const value) +{ + m_Id = value; + m_IdIsSet = true; +} +bool Category::idIsSet() const +{ + return m_IdIsSet; +} +void Category::unsetId() +{ + m_IdIsSet = false; +} +std::string Category::getName() const +{ + return m_Name; +} +void Category::setName(std::string const& value) +{ + m_Name = value; + m_NameIsSet = true; +} +bool Category::nameIsSet() const +{ + return m_NameIsSet; +} +void Category::unsetName() +{ + m_NameIsSet = false; +} + + +} // namespace org::openapitools::server::model + diff --git a/samples/server/petstore/cpp-pistache-everything/model/Order.h b/samples/server/petstore/cpp-pistache-everything/model/Order.h index 78a6c8805bbe..e69de29bb2d1 100644 --- a/samples/server/petstore/cpp-pistache-everything/model/Order.h +++ b/samples/server/petstore/cpp-pistache-everything/model/Order.h @@ -1,124 +0,0 @@ -/** -* OpenAPI Petstore -* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ -/* - * Order.h - * - * An order for a pets from the pet store - */ - -#ifndef Order_H_ -#define Order_H_ - - -#include -#include - -namespace org::openapitools::server::model -{ - -/// -/// An order for a pets from the pet store -/// -class Order -{ -public: - Order(); - virtual ~Order() = default; - - - /// - /// Validate the current data in the model. Throws a ValidationException on failure. - /// - void validate() const; - - /// - /// Validate the current data in the model. Returns false on error and writes an error - /// message into the given stringstream. - /// - bool validate(std::stringstream& msg) const; - - /// - /// Helper overload for validate. Used when one model stores another model and calls it's validate. - /// Not meant to be called outside that case. - /// - bool validate(std::stringstream& msg, const std::string& pathPrefix) const; - - bool operator==(const Order& rhs) const; - bool operator!=(const Order& rhs) const; - - ///////////////////////////////////////////// - /// Order members - - /// - /// - /// - int64_t getId() const; - void setId(int64_t const value); - bool idIsSet() const; - void unsetId(); - /// - /// - /// - int64_t getPetId() const; - void setPetId(int64_t const value); - bool petIdIsSet() const; - void unsetPetId(); - /// - /// - /// - int32_t getQuantity() const; - void setQuantity(int32_t const value); - bool quantityIsSet() const; - void unsetQuantity(); - /// - /// - /// - std::string getShipDate() const; - void setShipDate(std::string const& value); - bool shipDateIsSet() const; - void unsetShipDate(); - /// - /// Order Status - /// - std::string getStatus() const; - void setStatus(std::string const& value); - bool statusIsSet() const; - void unsetStatus(); - /// - /// - /// - bool isComplete() const; - void setComplete(bool const value); - bool completeIsSet() const; - void unsetComplete(); - - friend void to_json(nlohmann::json& j, const Order& o); - friend void from_json(const nlohmann::json& j, Order& o); -protected: - int64_t m_Id; - bool m_IdIsSet; - int64_t m_PetId; - bool m_PetIdIsSet; - int32_t m_Quantity; - bool m_QuantityIsSet; - std::string m_ShipDate; - bool m_ShipDateIsSet; - std::string m_Status; - bool m_StatusIsSet; - bool m_Complete; - bool m_CompleteIsSet; - -}; - -} // namespace org::openapitools::server::model - -#endif /* Order_H_ */ diff --git a/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.h b/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.h index df53df3c2be7..e69de29bb2d1 100644 --- a/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.h +++ b/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.h @@ -1,77 +0,0 @@ -/** -* Test swagger file -* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ -/* - * OuterType.h - * - * - */ - -#ifndef OuterType_H_ -#define OuterType_H_ - - -#include "MiddleType.h" -#include - -namespace org::openapitools::server::model -{ - -/// -/// -/// -class OuterType -{ -public: - OuterType(); - virtual ~OuterType() = default; - - - /// - /// Validate the current data in the model. Throws a ValidationException on failure. - /// - void validate() const; - - /// - /// Validate the current data in the model. Returns false on error and writes an error - /// message into the given stringstream. - /// - bool validate(std::stringstream& msg) const; - - /// - /// Helper overload for validate. Used when one model stores another model and calls it's validate. - /// Not meant to be called outside that case. - /// - bool validate(std::stringstream& msg, const std::string& pathPrefix) const; - - bool operator==(const OuterType& rhs) const; - bool operator!=(const OuterType& rhs) const; - - ///////////////////////////////////////////// - /// OuterType members - - /// - /// - /// - org::openapitools::server::model::MiddleType getMiddle() const; - void setMiddle(org::openapitools::server::model::MiddleType const& value); - - friend void to_json(nlohmann::json& j, const OuterType& o); - friend void from_json(const nlohmann::json& j, OuterType& o); -protected: - org::openapitools::server::model::MiddleType m_Middle; - - -}; - -} // namespace org::openapitools::server::model - -#endif /* OuterType_H_ */ From bdbe53c3f139251ed6d9d868c5763ecaa74c6278 Mon Sep 17 00:00:00 2001 From: Pavel Slabko Date: Thu, 12 Feb 2026 15:09:24 +0100 Subject: [PATCH 3/5] rebased --- .../c/bearerAuth/include/keyValuePair.h | 17 + .../client/others/c/bearerAuth/model/object.c | 51 - samples/client/others/c/bearerAuth/src/list.c | 200 +++ .../apex/config/project-scratch-def.json | 8 + samples/client/petstore/bash/docs/EnumTest.md | 14 + samples/client/petstore/bash/docs/MapTest.md | 13 - .../model/model_with_set_propertes.h | 41 + .../c-useJsonUnformatted/model/order.c | 233 ++++ .../petstore/c-useJsonUnformatted/model/pet.c | 335 ----- .../client/petstore/c/model/api_response.c | 142 ++ samples/client/petstore/c/model/category.c | 113 -- samples/client/petstore/c/model/category.h | 40 + .../petstore/cpp-oatpp/api/StoreApi.hpp | 77 -- .../client/petstore/cpp-oatpp/model/Tag.hpp | 51 + .../client/PFXApiResponse.cpp | 160 --- .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/Program.cs | 33 + .../src/Org.OpenAPITools/appsettings.json | 8 + .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/Program.cs | 33 + .../src/Org.OpenAPITools/appsettings.json | 8 + .../Filters/BasePathFilter.cs | 60 - .../src/Org.OpenAPITools/Program.cs | 33 + .../src/Org.OpenAPITools/appsettings.json | 8 + .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/Program.cs | 33 + .../src/Org.OpenAPITools/appsettings.json | 8 + .../src/Org.OpenAPITools/Dockerfile | 32 + .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/Program.cs | 33 + .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/appsettings.json | 8 + .../OpenApi/TypeExtensions.cs | 61 + .../src/Org.OpenAPITools/Program.cs | 33 + .../wwwroot/openapi-original.json | 1203 ----------------- .../.openapi-generator/VERSION | 2 +- .../Formatters/InputFormatterStream.cs | 45 + .../Org.OpenAPITools/Org.OpenAPITools.nuspec | 20 + .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/Program.cs | 33 + .../src/Org.OpenAPITools/appsettings.json | 8 + .../src/Org.OpenAPITools/Dockerfile | 32 + .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/Startup.cs | 150 ++ .../src/Org.OpenAPITools/Dockerfile | 32 + .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/Program.cs | 33 + .../src/Org.OpenAPITools/Program.cs | 33 + .../src/Org.OpenAPITools/appsettings.json | 8 + .../wwwroot/openapi-original.json | 1203 ----------------- .../Org.OpenAPITools/Org.OpenAPITools.csproj | 27 + .../src/Org.OpenAPITools/Program.cs | 33 + .../wwwroot/openapi-original.json | 1203 ----------------- .../src/Org.OpenAPITools/Dockerfile | 32 + .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/Program.cs | 33 + .../.openapi-generator/VERSION | 2 +- .../Formatters/InputFormatterStream.cs | 45 + .../Org.OpenAPITools/Org.OpenAPITools.nuspec | 20 + .../GeneratePathParamsValidationFilter.cs | 107 -- .../src/Org.OpenAPITools/Program.cs | 33 + .../src/Org.OpenAPITools/appsettings.json | 8 + .../Properties/launchSettings.json | 30 + .../wwwroot/openapi-original.json | 1021 -------------- .../server/petstore/cpp-oatpp/model/Order.hpp | 59 - .../cpp-pistache-everything/model/Order.cpp | 251 ---- .../cpp-pistache-everything/model/Order.h | 124 ++ .../api/StoreApi.cpp | 103 -- .../model/OuterType.cpp | 94 ++ .../model/OuterType.h | 77 ++ .../petstore/cpp-pistache/model/Category.cpp | 135 -- 71 files changed, 2029 insertions(+), 7059 deletions(-) diff --git a/samples/client/others/c/bearerAuth/include/keyValuePair.h b/samples/client/others/c/bearerAuth/include/keyValuePair.h index e69de29bb2d1..cb839f29cdcf 100644 --- a/samples/client/others/c/bearerAuth/include/keyValuePair.h +++ b/samples/client/others/c/bearerAuth/include/keyValuePair.h @@ -0,0 +1,17 @@ +#ifndef _keyValuePair_H_ +#define _keyValuePair_H_ + +#include + +typedef struct keyValuePair_t { + char* key; + void* value; +} keyValuePair_t; + +keyValuePair_t *keyValuePair_create(char *key, void *value); + +keyValuePair_t* keyValuePair_create_allocate(char* key, double value); + +void keyValuePair_free(keyValuePair_t *keyValuePair); + +#endif /* _keyValuePair_H_ */ \ No newline at end of file diff --git a/samples/client/others/c/bearerAuth/model/object.c b/samples/client/others/c/bearerAuth/model/object.c index ff293bcdac85..e69de29bb2d1 100644 --- a/samples/client/others/c/bearerAuth/model/object.c +++ b/samples/client/others/c/bearerAuth/model/object.c @@ -1,51 +0,0 @@ -#include -#include -#include -#include "object.h" - -object_t *object_create() { - object_t *object = calloc(1, sizeof(object_t)); - - return object; -} - -void object_free(object_t *object) { - if (!object) { - return ; - } - - if (object->temporary) { - free(object->temporary); - object->temporary = NULL; - } - - free (object); -} - -cJSON *object_convertToJSON(object_t *object) { - if (!object) { - return NULL; - } - - if (!object->temporary) { - return cJSON_Parse("null"); - } - - return cJSON_Parse(object->temporary); -} - -object_t *object_parseFromJSON(cJSON *json){ - if (!json) { - goto end; - } - - object_t *object = object_create(); - if (!object) { - goto end; - } - object->temporary = cJSON_Print(json); - return object; - -end: - return NULL; -} diff --git a/samples/client/others/c/bearerAuth/src/list.c b/samples/client/others/c/bearerAuth/src/list.c index e69de29bb2d1..7053ff122dfc 100644 --- a/samples/client/others/c/bearerAuth/src/list.c +++ b/samples/client/others/c/bearerAuth/src/list.c @@ -0,0 +1,200 @@ +#include +#include +#include +#include + +#include "../include/list.h" +static listEntry_t *listEntry_create(void *data) { + listEntry_t *createdListEntry = malloc(sizeof(listEntry_t)); + if(createdListEntry == NULL) { + // TODO Malloc Failure + return NULL; + } + createdListEntry->data = data; + + return createdListEntry; +} + +void listEntry_free(listEntry_t *listEntry, void *additionalData) { + free(listEntry); +} + +void listEntry_printAsInt(listEntry_t *listEntry, void *additionalData) { + printf("%i\n", *(int *)listEntry->data); +} + +list_t *list_createList() { + list_t *createdList = malloc(sizeof(list_t)); + if(createdList == NULL) { + // TODO Malloc Failure + return NULL; + } + createdList->firstEntry = NULL; + createdList->lastEntry = NULL; + createdList->count = 0; + + return createdList; +} + +void list_iterateThroughListForward(list_t *list, + void (*operationToPerform)( + listEntry_t *, + void *callbackFunctionUsedData), + void *additionalDataNeededForCallbackFunction) +{ + listEntry_t *currentListEntry = list->firstEntry; + listEntry_t *nextListEntry; + + if(currentListEntry == NULL) { + return; + } + + nextListEntry = currentListEntry->nextListEntry; + + operationToPerform(currentListEntry, + additionalDataNeededForCallbackFunction); + currentListEntry = nextListEntry; + + while(currentListEntry != NULL) { + nextListEntry = currentListEntry->nextListEntry; + operationToPerform(currentListEntry, + additionalDataNeededForCallbackFunction); + currentListEntry = nextListEntry; + } +} + +void list_iterateThroughListBackward(list_t *list, + void (*operationToPerform)( + listEntry_t *, + void *callbackFunctionUsedData), + void *additionalDataNeededForCallbackFunction) +{ + listEntry_t *currentListEntry = list->lastEntry; + listEntry_t *nextListEntry = currentListEntry->prevListEntry; + + if(currentListEntry == NULL) { + return; + } + + operationToPerform(currentListEntry, + additionalDataNeededForCallbackFunction); + currentListEntry = nextListEntry; + + while(currentListEntry != NULL) { + nextListEntry = currentListEntry->prevListEntry; + operationToPerform(currentListEntry, + additionalDataNeededForCallbackFunction); + currentListEntry = nextListEntry; + } +} + +void list_freeList(list_t *list) { + if(list){ + list_iterateThroughListForward(list, listEntry_free, NULL); + free(list); + } +} + +void list_addElement(list_t *list, void *dataToAddInList) { + listEntry_t *newListEntry = listEntry_create(dataToAddInList); + if(newListEntry == NULL) { + // TODO Malloc Failure + return; + } + if(list->firstEntry == NULL) { + list->firstEntry = newListEntry; + list->lastEntry = newListEntry; + + newListEntry->prevListEntry = NULL; + newListEntry->nextListEntry = NULL; + + list->count++; + + return; + } + + list->lastEntry->nextListEntry = newListEntry; + newListEntry->prevListEntry = list->lastEntry; + newListEntry->nextListEntry = NULL; + list->lastEntry = newListEntry; + + list->count++; +} + +void list_removeElement(list_t *list, listEntry_t *elementToRemove) { + listEntry_t *elementBeforeElementToRemove = + elementToRemove->prevListEntry; + listEntry_t *elementAfterElementToRemove = + elementToRemove->nextListEntry; + + if(elementBeforeElementToRemove != NULL) { + elementBeforeElementToRemove->nextListEntry = + elementAfterElementToRemove; + } else { + list->firstEntry = elementAfterElementToRemove; + } + + if(elementAfterElementToRemove != NULL) { + elementAfterElementToRemove->prevListEntry = + elementBeforeElementToRemove; + } else { + list->lastEntry = elementBeforeElementToRemove; + } + + listEntry_free(elementToRemove, NULL); + + list->count--; +} + +listEntry_t *list_getElementAt(list_t *list, long indexOfElement) { + listEntry_t *currentListEntry; + + if((list->count / 2) > indexOfElement) { + currentListEntry = list->firstEntry; + + for(int i = 0; i < indexOfElement; i++) { + currentListEntry = currentListEntry->nextListEntry; + } + + return currentListEntry; + } else { + currentListEntry = list->lastEntry; + + for(int i = 1; i < (list->count - indexOfElement); i++) { + currentListEntry = currentListEntry->prevListEntry; + } + + return currentListEntry; + } +} + +char* findStrInStrList(list_t *strList, const char *str) +{ + if (!strList || !str) { + return NULL; + } + + listEntry_t* listEntry = NULL; + list_ForEach(listEntry, strList) { + if (strstr(listEntry->data, str) != NULL) { + return listEntry->data; + } + } + + return NULL; +} + +void clear_and_free_string_list(list_t *list) +{ + if (!list) { + return; + } + + listEntry_t *listEntry = NULL; + list_ForEach(listEntry, list) { + char *list_item = listEntry->data; + free(list_item); + list_item = NULL; + } + list_freeList(list); +} diff --git a/samples/client/petstore/apex/config/project-scratch-def.json b/samples/client/petstore/apex/config/project-scratch-def.json index e69de29bb2d1..36aace552669 100644 --- a/samples/client/petstore/apex/config/project-scratch-def.json +++ b/samples/client/petstore/apex/config/project-scratch-def.json @@ -0,0 +1,8 @@ +{ + "orgName": "muenzpraeger - René Winkelmeyer", + "edition": "Developer", + "orgPreferences": { + "enabled": ["S1DesktopEnabled"], + "disabled": ["S1EncryptedStoragePref2"] + } +} diff --git a/samples/client/petstore/bash/docs/EnumTest.md b/samples/client/petstore/bash/docs/EnumTest.md index e69de29bb2d1..30b30efa7307 100644 --- a/samples/client/petstore/bash/docs/EnumTest.md +++ b/samples/client/petstore/bash/docs/EnumTest.md @@ -0,0 +1,14 @@ +# Enum_Test + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumUnderscorestring** | **string** | | [optional] [default to null] +**enumUnderscorestringUnderscorerequired** | **string** | | [default to null] +**enumUnderscoreinteger** | **integer** | | [optional] [default to null] +**enumUnderscorenumber** | **float** | | [optional] [default to null] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/bash/docs/MapTest.md b/samples/client/petstore/bash/docs/MapTest.md index e4ed4a233829..e69de29bb2d1 100644 --- a/samples/client/petstore/bash/docs/MapTest.md +++ b/samples/client/petstore/bash/docs/MapTest.md @@ -1,13 +0,0 @@ -# MapTest - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**mapUnderscoremapUnderscoreofUnderscorestring** | **map[String, map[String, string]]** | | [optional] [default to null] -**mapUnderscoreofUnderscoreenumUnderscorestring** | **map[String, string]** | | [optional] [default to null] -**directUnderscoremap** | **map[String, boolean]** | | [optional] [default to null] -**indirectUnderscoremap** | **map[String, boolean]** | | [optional] [default to null] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/client/petstore/c-useJsonUnformatted/model/model_with_set_propertes.h b/samples/client/petstore/c-useJsonUnformatted/model/model_with_set_propertes.h index e69de29bb2d1..aa82893b94bb 100644 --- a/samples/client/petstore/c-useJsonUnformatted/model/model_with_set_propertes.h +++ b/samples/client/petstore/c-useJsonUnformatted/model/model_with_set_propertes.h @@ -0,0 +1,41 @@ +/* + * model_with_set_propertes.h + * + * to test set properties + */ + +#ifndef _model_with_set_propertes_H_ +#define _model_with_set_propertes_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct model_with_set_propertes_t model_with_set_propertes_t; + +#include "tag.h" + + + +typedef struct model_with_set_propertes_t { + list_t *tag_set; //nonprimitive container + list_t *string_set; //primitive container + + int _library_owned; // Is the library responsible for freeing this object? +} model_with_set_propertes_t; + +__attribute__((deprecated)) model_with_set_propertes_t *model_with_set_propertes_create( + list_t *tag_set, + list_t *string_set +); + +void model_with_set_propertes_free(model_with_set_propertes_t *model_with_set_propertes); + +model_with_set_propertes_t *model_with_set_propertes_parseFromJSON(cJSON *model_with_set_propertesJSON); + +cJSON *model_with_set_propertes_convertToJSON(model_with_set_propertes_t *model_with_set_propertes); + +#endif /* _model_with_set_propertes_H_ */ + diff --git a/samples/client/petstore/c-useJsonUnformatted/model/order.c b/samples/client/petstore/c-useJsonUnformatted/model/order.c index e69de29bb2d1..d67d1d47c714 100644 --- a/samples/client/petstore/c-useJsonUnformatted/model/order.c +++ b/samples/client/petstore/c-useJsonUnformatted/model/order.c @@ -0,0 +1,233 @@ +#include +#include +#include +#include "order.h" + + +char* order_status_ToString(openapi_petstore_order_STATUS_e status) { + char* statusArray[] = { "NULL", "placed", "approved", "delivered" }; + return statusArray[status]; +} + +openapi_petstore_order_STATUS_e order_status_FromString(char* status){ + int stringToReturn = 0; + char *statusArray[] = { "NULL", "placed", "approved", "delivered" }; + size_t sizeofArray = sizeof(statusArray) / sizeof(statusArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(status, statusArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +static order_t *order_create_internal( + long id, + long pet_id, + int quantity, + char *ship_date, + openapi_petstore_order_STATUS_e status, + int complete + ) { + order_t *order_local_var = malloc(sizeof(order_t)); + if (!order_local_var) { + return NULL; + } + order_local_var->id = id; + order_local_var->pet_id = pet_id; + order_local_var->quantity = quantity; + order_local_var->ship_date = ship_date; + order_local_var->status = status; + order_local_var->complete = complete; + + order_local_var->_library_owned = 1; + return order_local_var; +} + +__attribute__((deprecated)) order_t *order_create( + long id, + long pet_id, + int quantity, + char *ship_date, + openapi_petstore_order_STATUS_e status, + int complete + ) { + return order_create_internal ( + id, + pet_id, + quantity, + ship_date, + status, + complete + ); +} + +void order_free(order_t *order) { + if(NULL == order){ + return ; + } + if(order->_library_owned != 1){ + fprintf(stderr, "WARNING: %s() does NOT free objects allocated by the user\n", "order_free"); + return ; + } + listEntry_t *listEntry; + if (order->ship_date) { + free(order->ship_date); + order->ship_date = NULL; + } + free(order); +} + +cJSON *order_convertToJSON(order_t *order) { + cJSON *item = cJSON_CreateObject(); + + // order->id + if(order->id) { + if(cJSON_AddNumberToObject(item, "id", order->id) == NULL) { + goto fail; //Numeric + } + } + + + // order->pet_id + if(order->pet_id) { + if(cJSON_AddNumberToObject(item, "petId", order->pet_id) == NULL) { + goto fail; //Numeric + } + } + + + // order->quantity + if(order->quantity) { + if(cJSON_AddNumberToObject(item, "quantity", order->quantity) == NULL) { + goto fail; //Numeric + } + } + + + // order->ship_date + if(order->ship_date) { + if(cJSON_AddStringToObject(item, "shipDate", order->ship_date) == NULL) { + goto fail; //Date-Time + } + } + + + // order->status + if(order->status != openapi_petstore_order_STATUS_NULL) { + if(cJSON_AddStringToObject(item, "status", order_status_ToString(order->status)) == NULL) + { + goto fail; //Enum + } + } + + + // order->complete + if(order->complete) { + if(cJSON_AddBoolToObject(item, "complete", order->complete) == NULL) { + goto fail; //Bool + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +order_t *order_parseFromJSON(cJSON *orderJSON){ + + order_t *order_local_var = NULL; + + // order->id + cJSON *id = cJSON_GetObjectItemCaseSensitive(orderJSON, "id"); + if (cJSON_IsNull(id)) { + id = NULL; + } + if (id) { + if(!cJSON_IsNumber(id)) + { + goto end; //Numeric + } + } + + // order->pet_id + cJSON *pet_id = cJSON_GetObjectItemCaseSensitive(orderJSON, "petId"); + if (cJSON_IsNull(pet_id)) { + pet_id = NULL; + } + if (pet_id) { + if(!cJSON_IsNumber(pet_id)) + { + goto end; //Numeric + } + } + + // order->quantity + cJSON *quantity = cJSON_GetObjectItemCaseSensitive(orderJSON, "quantity"); + if (cJSON_IsNull(quantity)) { + quantity = NULL; + } + if (quantity) { + if(!cJSON_IsNumber(quantity)) + { + goto end; //Numeric + } + } + + // order->ship_date + cJSON *ship_date = cJSON_GetObjectItemCaseSensitive(orderJSON, "shipDate"); + if (cJSON_IsNull(ship_date)) { + ship_date = NULL; + } + if (ship_date) { + if(!cJSON_IsString(ship_date) && !cJSON_IsNull(ship_date)) + { + goto end; //DateTime + } + } + + // order->status + cJSON *status = cJSON_GetObjectItemCaseSensitive(orderJSON, "status"); + if (cJSON_IsNull(status)) { + status = NULL; + } + openapi_petstore_order_STATUS_e statusVariable; + if (status) { + if(!cJSON_IsString(status)) + { + goto end; //Enum + } + statusVariable = order_status_FromString(status->valuestring); + } + + // order->complete + cJSON *complete = cJSON_GetObjectItemCaseSensitive(orderJSON, "complete"); + if (cJSON_IsNull(complete)) { + complete = NULL; + } + if (complete) { + if(!cJSON_IsBool(complete)) + { + goto end; //Bool + } + } + + + order_local_var = order_create_internal ( + id ? id->valuedouble : 0, + pet_id ? pet_id->valuedouble : 0, + quantity ? quantity->valuedouble : 0, + ship_date && !cJSON_IsNull(ship_date) ? strdup(ship_date->valuestring) : NULL, + status ? statusVariable : openapi_petstore_order_STATUS_NULL, + complete ? complete->valueint : 0 + ); + + return order_local_var; +end: + return NULL; + +} diff --git a/samples/client/petstore/c-useJsonUnformatted/model/pet.c b/samples/client/petstore/c-useJsonUnformatted/model/pet.c index b561634cb529..e69de29bb2d1 100644 --- a/samples/client/petstore/c-useJsonUnformatted/model/pet.c +++ b/samples/client/petstore/c-useJsonUnformatted/model/pet.c @@ -1,335 +0,0 @@ -#include -#include -#include -#include "pet.h" - - -char* pet_status_ToString(openapi_petstore_pet_STATUS_e status) { - char* statusArray[] = { "NULL", "available", "pending", "sold" }; - return statusArray[status]; -} - -openapi_petstore_pet_STATUS_e pet_status_FromString(char* status){ - int stringToReturn = 0; - char *statusArray[] = { "NULL", "available", "pending", "sold" }; - size_t sizeofArray = sizeof(statusArray) / sizeof(statusArray[0]); - while(stringToReturn < sizeofArray) { - if(strcmp(status, statusArray[stringToReturn]) == 0) { - return stringToReturn; - } - stringToReturn++; - } - return 0; -} - -static pet_t *pet_create_internal( - long id, - category_t *category, - char *name, - list_t *photo_urls, - list_t *tags, - openapi_petstore_pet_STATUS_e status - ) { - pet_t *pet_local_var = malloc(sizeof(pet_t)); - if (!pet_local_var) { - return NULL; - } - pet_local_var->id = id; - pet_local_var->category = category; - pet_local_var->name = name; - pet_local_var->photo_urls = photo_urls; - pet_local_var->tags = tags; - pet_local_var->status = status; - - pet_local_var->_library_owned = 1; - return pet_local_var; -} - -__attribute__((deprecated)) pet_t *pet_create( - long id, - category_t *category, - char *name, - list_t *photo_urls, - list_t *tags, - openapi_petstore_pet_STATUS_e status - ) { - return pet_create_internal ( - id, - category, - name, - photo_urls, - tags, - status - ); -} - -void pet_free(pet_t *pet) { - if(NULL == pet){ - return ; - } - if(pet->_library_owned != 1){ - fprintf(stderr, "WARNING: %s() does NOT free objects allocated by the user\n", "pet_free"); - return ; - } - listEntry_t *listEntry; - if (pet->category) { - category_free(pet->category); - pet->category = NULL; - } - if (pet->name) { - free(pet->name); - pet->name = NULL; - } - if (pet->photo_urls) { - list_ForEach(listEntry, pet->photo_urls) { - free(listEntry->data); - } - list_freeList(pet->photo_urls); - pet->photo_urls = NULL; - } - if (pet->tags) { - list_ForEach(listEntry, pet->tags) { - tag_free(listEntry->data); - } - list_freeList(pet->tags); - pet->tags = NULL; - } - free(pet); -} - -cJSON *pet_convertToJSON(pet_t *pet) { - cJSON *item = cJSON_CreateObject(); - - // pet->id - if(pet->id) { - if(cJSON_AddNumberToObject(item, "id", pet->id) == NULL) { - goto fail; //Numeric - } - } - - - // pet->category - if(pet->category) { - cJSON *category_local_JSON = category_convertToJSON(pet->category); - if(category_local_JSON == NULL) { - goto fail; //model - } - cJSON_AddItemToObject(item, "category", category_local_JSON); - if(item->child == NULL) { - goto fail; - } - } - - - // pet->name - if (!pet->name) { - goto fail; - } - if(cJSON_AddStringToObject(item, "name", pet->name) == NULL) { - goto fail; //String - } - - - // pet->photo_urls - if (!pet->photo_urls) { - goto fail; - } - cJSON *photo_urls = cJSON_AddArrayToObject(item, "photoUrls"); - if(photo_urls == NULL) { - goto fail; //primitive container - } - - listEntry_t *photo_urlsListEntry; - list_ForEach(photo_urlsListEntry, pet->photo_urls) { - if(cJSON_AddStringToObject(photo_urls, "", photo_urlsListEntry->data) == NULL) - { - goto fail; - } - } - - - // pet->tags - if(pet->tags) { - cJSON *tags = cJSON_AddArrayToObject(item, "tags"); - if(tags == NULL) { - goto fail; //nonprimitive container - } - - listEntry_t *tagsListEntry; - if (pet->tags) { - list_ForEach(tagsListEntry, pet->tags) { - cJSON *itemLocal = tag_convertToJSON(tagsListEntry->data); - if(itemLocal == NULL) { - goto fail; - } - cJSON_AddItemToArray(tags, itemLocal); - } - } - } - - - // pet->status - if(pet->status != openapi_petstore_pet_STATUS_NULL) { - if(cJSON_AddStringToObject(item, "status", pet_status_ToString(pet->status)) == NULL) - { - goto fail; //Enum - } - } - - return item; -fail: - if (item) { - cJSON_Delete(item); - } - return NULL; -} - -pet_t *pet_parseFromJSON(cJSON *petJSON){ - - pet_t *pet_local_var = NULL; - - // define the local variable for pet->category - category_t *category_local_nonprim = NULL; - - // define the local list for pet->photo_urls - list_t *photo_urlsList = NULL; - - // define the local list for pet->tags - list_t *tagsList = NULL; - - // pet->id - cJSON *id = cJSON_GetObjectItemCaseSensitive(petJSON, "id"); - if (cJSON_IsNull(id)) { - id = NULL; - } - if (id) { - if(!cJSON_IsNumber(id)) - { - goto end; //Numeric - } - } - - // pet->category - cJSON *category = cJSON_GetObjectItemCaseSensitive(petJSON, "category"); - if (cJSON_IsNull(category)) { - category = NULL; - } - if (category) { - category_local_nonprim = category_parseFromJSON(category); //nonprimitive - } - - // pet->name - cJSON *name = cJSON_GetObjectItemCaseSensitive(petJSON, "name"); - if (cJSON_IsNull(name)) { - name = NULL; - } - if (!name) { - goto end; - } - - - if(!cJSON_IsString(name)) - { - goto end; //String - } - - // pet->photo_urls - cJSON *photo_urls = cJSON_GetObjectItemCaseSensitive(petJSON, "photoUrls"); - if (cJSON_IsNull(photo_urls)) { - photo_urls = NULL; - } - if (!photo_urls) { - goto end; - } - - - cJSON *photo_urls_local = NULL; - if(!cJSON_IsArray(photo_urls)) { - goto end;//primitive container - } - photo_urlsList = list_createList(); - - cJSON_ArrayForEach(photo_urls_local, photo_urls) - { - if(!cJSON_IsString(photo_urls_local)) - { - goto end; - } - list_addElement(photo_urlsList , strdup(photo_urls_local->valuestring)); - } - - // pet->tags - cJSON *tags = cJSON_GetObjectItemCaseSensitive(petJSON, "tags"); - if (cJSON_IsNull(tags)) { - tags = NULL; - } - if (tags) { - cJSON *tags_local_nonprimitive = NULL; - if(!cJSON_IsArray(tags)){ - goto end; //nonprimitive container - } - - tagsList = list_createList(); - - cJSON_ArrayForEach(tags_local_nonprimitive,tags ) - { - if(!cJSON_IsObject(tags_local_nonprimitive)){ - goto end; - } - tag_t *tagsItem = tag_parseFromJSON(tags_local_nonprimitive); - - list_addElement(tagsList, tagsItem); - } - } - - // pet->status - cJSON *status = cJSON_GetObjectItemCaseSensitive(petJSON, "status"); - if (cJSON_IsNull(status)) { - status = NULL; - } - openapi_petstore_pet_STATUS_e statusVariable; - if (status) { - if(!cJSON_IsString(status)) - { - goto end; //Enum - } - statusVariable = pet_status_FromString(status->valuestring); - } - - - pet_local_var = pet_create_internal ( - id ? id->valuedouble : 0, - category ? category_local_nonprim : NULL, - strdup(name->valuestring), - photo_urlsList, - tags ? tagsList : NULL, - status ? statusVariable : openapi_petstore_pet_STATUS_NULL - ); - - return pet_local_var; -end: - if (category_local_nonprim) { - category_free(category_local_nonprim); - category_local_nonprim = NULL; - } - if (photo_urlsList) { - listEntry_t *listEntry = NULL; - list_ForEach(listEntry, photo_urlsList) { - free(listEntry->data); - listEntry->data = NULL; - } - list_freeList(photo_urlsList); - photo_urlsList = NULL; - } - if (tagsList) { - listEntry_t *listEntry = NULL; - list_ForEach(listEntry, tagsList) { - tag_free(listEntry->data); - listEntry->data = NULL; - } - list_freeList(tagsList); - tagsList = NULL; - } - return NULL; - -} diff --git a/samples/client/petstore/c/model/api_response.c b/samples/client/petstore/c/model/api_response.c index e69de29bb2d1..d0169c84f5b2 100644 --- a/samples/client/petstore/c/model/api_response.c +++ b/samples/client/petstore/c/model/api_response.c @@ -0,0 +1,142 @@ +#include +#include +#include +#include "api_response.h" + + + +static api_response_t *api_response_create_internal( + int code, + char *type, + char *message + ) { + api_response_t *api_response_local_var = malloc(sizeof(api_response_t)); + if (!api_response_local_var) { + return NULL; + } + api_response_local_var->code = code; + api_response_local_var->type = type; + api_response_local_var->message = message; + + api_response_local_var->_library_owned = 1; + return api_response_local_var; +} + +__attribute__((deprecated)) api_response_t *api_response_create( + int code, + char *type, + char *message + ) { + return api_response_create_internal ( + code, + type, + message + ); +} + +void api_response_free(api_response_t *api_response) { + if(NULL == api_response){ + return ; + } + if(api_response->_library_owned != 1){ + fprintf(stderr, "WARNING: %s() does NOT free objects allocated by the user\n", "api_response_free"); + return ; + } + listEntry_t *listEntry; + if (api_response->type) { + free(api_response->type); + api_response->type = NULL; + } + if (api_response->message) { + free(api_response->message); + api_response->message = NULL; + } + free(api_response); +} + +cJSON *api_response_convertToJSON(api_response_t *api_response) { + cJSON *item = cJSON_CreateObject(); + + // api_response->code + if(api_response->code) { + if(cJSON_AddNumberToObject(item, "code", api_response->code) == NULL) { + goto fail; //Numeric + } + } + + + // api_response->type + if(api_response->type) { + if(cJSON_AddStringToObject(item, "type", api_response->type) == NULL) { + goto fail; //String + } + } + + + // api_response->message + if(api_response->message) { + if(cJSON_AddStringToObject(item, "message", api_response->message) == NULL) { + goto fail; //String + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +api_response_t *api_response_parseFromJSON(cJSON *api_responseJSON){ + + api_response_t *api_response_local_var = NULL; + + // api_response->code + cJSON *code = cJSON_GetObjectItemCaseSensitive(api_responseJSON, "code"); + if (cJSON_IsNull(code)) { + code = NULL; + } + if (code) { + if(!cJSON_IsNumber(code)) + { + goto end; //Numeric + } + } + + // api_response->type + cJSON *type = cJSON_GetObjectItemCaseSensitive(api_responseJSON, "type"); + if (cJSON_IsNull(type)) { + type = NULL; + } + if (type) { + if(!cJSON_IsString(type) && !cJSON_IsNull(type)) + { + goto end; //String + } + } + + // api_response->message + cJSON *message = cJSON_GetObjectItemCaseSensitive(api_responseJSON, "message"); + if (cJSON_IsNull(message)) { + message = NULL; + } + if (message) { + if(!cJSON_IsString(message) && !cJSON_IsNull(message)) + { + goto end; //String + } + } + + + api_response_local_var = api_response_create_internal ( + code ? code->valuedouble : 0, + type && !cJSON_IsNull(type) ? strdup(type->valuestring) : NULL, + message && !cJSON_IsNull(message) ? strdup(message->valuestring) : NULL + ); + + return api_response_local_var; +end: + return NULL; + +} diff --git a/samples/client/petstore/c/model/category.c b/samples/client/petstore/c/model/category.c index 2b060a568015..e69de29bb2d1 100644 --- a/samples/client/petstore/c/model/category.c +++ b/samples/client/petstore/c/model/category.c @@ -1,113 +0,0 @@ -#include -#include -#include -#include "category.h" - - - -static category_t *category_create_internal( - long id, - char *name - ) { - category_t *category_local_var = malloc(sizeof(category_t)); - if (!category_local_var) { - return NULL; - } - category_local_var->id = id; - category_local_var->name = name; - - category_local_var->_library_owned = 1; - return category_local_var; -} - -__attribute__((deprecated)) category_t *category_create( - long id, - char *name - ) { - return category_create_internal ( - id, - name - ); -} - -void category_free(category_t *category) { - if(NULL == category){ - return ; - } - if(category->_library_owned != 1){ - fprintf(stderr, "WARNING: %s() does NOT free objects allocated by the user\n", "category_free"); - return ; - } - listEntry_t *listEntry; - if (category->name) { - free(category->name); - category->name = NULL; - } - free(category); -} - -cJSON *category_convertToJSON(category_t *category) { - cJSON *item = cJSON_CreateObject(); - - // category->id - if(category->id) { - if(cJSON_AddNumberToObject(item, "id", category->id) == NULL) { - goto fail; //Numeric - } - } - - - // category->name - if(category->name) { - if(cJSON_AddStringToObject(item, "name", category->name) == NULL) { - goto fail; //String - } - } - - return item; -fail: - if (item) { - cJSON_Delete(item); - } - return NULL; -} - -category_t *category_parseFromJSON(cJSON *categoryJSON){ - - category_t *category_local_var = NULL; - - // category->id - cJSON *id = cJSON_GetObjectItemCaseSensitive(categoryJSON, "id"); - if (cJSON_IsNull(id)) { - id = NULL; - } - if (id) { - if(!cJSON_IsNumber(id)) - { - goto end; //Numeric - } - } - - // category->name - cJSON *name = cJSON_GetObjectItemCaseSensitive(categoryJSON, "name"); - if (cJSON_IsNull(name)) { - name = NULL; - } - if (name) { - if(!cJSON_IsString(name) && !cJSON_IsNull(name)) - { - goto end; //String - } - } - - - category_local_var = category_create_internal ( - id ? id->valuedouble : 0, - name && !cJSON_IsNull(name) ? strdup(name->valuestring) : NULL - ); - - return category_local_var; -end: - return NULL; - -} diff --git a/samples/client/petstore/c/model/category.h b/samples/client/petstore/c/model/category.h index e69de29bb2d1..bd27e27e35a3 100644 --- a/samples/client/petstore/c/model/category.h +++ b/samples/client/petstore/c/model/category.h @@ -0,0 +1,40 @@ +/* + * category.h + * + * A category for a pet + */ + +#ifndef _category_H_ +#define _category_H_ + +#include +#include "../external/cJSON.h" +#include "../include/list.h" +#include "../include/keyValuePair.h" +#include "../include/binary.h" + +typedef struct category_t category_t; + + + + +typedef struct category_t { + long id; //numeric + char *name; // string + + int _library_owned; // Is the library responsible for freeing this object? +} category_t; + +__attribute__((deprecated)) category_t *category_create( + long id, + char *name +); + +void category_free(category_t *category); + +category_t *category_parseFromJSON(cJSON *categoryJSON); + +cJSON *category_convertToJSON(category_t *category); + +#endif /* _category_H_ */ + diff --git a/samples/client/petstore/cpp-oatpp/api/StoreApi.hpp b/samples/client/petstore/cpp-oatpp/api/StoreApi.hpp index f48ec25ab0ab..e69de29bb2d1 100644 --- a/samples/client/petstore/cpp-oatpp/api/StoreApi.hpp +++ b/samples/client/petstore/cpp-oatpp/api/StoreApi.hpp @@ -1,77 +0,0 @@ -/** -* OpenAPI Petstore -* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ -/* - * StoreApi.h - * - * - */ - -#ifndef StoreApi_H_ -#define StoreApi_H_ - - - -#include "oatpp/web/client/ApiClient.hpp" -#include "oatpp/web/protocol/http/outgoing/MultipartBody.hpp" -#include "oatpp/core/macro/codegen.hpp" - -#include "Order.hpp" - -#include OATPP_CODEGEN_BEGIN(ApiClient) ///< Begin code-gen section - -namespace org::openapitools::client::api -{ - -class StoreApi : public oatpp::web::client::ApiClient { -public: - - API_CLIENT_INIT(StoreApi) - - /// - /// Delete purchase order by ID - /// - /// - /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - /// - /// ID of the order that needs to be deleted - API_CALL("DELETE", "/store/order/{orderId}", delete_order, PATH(oatpp::String, orderId)) - /// - /// Returns pet inventories by status - /// - /// - /// Returns a map of status codes to quantities - /// - API_CALL("GET", "/store/inventory", get_inventory) - /// - /// Find purchase order by ID - /// - /// - /// For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions - /// - /// ID of pet that needs to be fetched - API_CALL("GET", "/store/order/{orderId}", get_order_by_id, PATH(oatpp::Int64, orderId)) - /// - /// Place an order for a pet - /// - /// - /// - /// - /// order placed for purchasing the pet - API_CALL("POST", "/store/order", place_order, BODY_DTO(oatpp::Object, order)) -}; - -#include OATPP_CODEGEN_END(ApiClient) ///< End code-gen section - -} // namespace org::openapitools::client::api - -#endif /* StoreApi_H_ */ - diff --git a/samples/client/petstore/cpp-oatpp/model/Tag.hpp b/samples/client/petstore/cpp-oatpp/model/Tag.hpp index e69de29bb2d1..befd6854d51e 100644 --- a/samples/client/petstore/cpp-oatpp/model/Tag.hpp +++ b/samples/client/petstore/cpp-oatpp/model/Tag.hpp @@ -0,0 +1,51 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +/* + * Tag.h + * + * A tag for a pet + */ + +#ifndef Tag_H_ +#define Tag_H_ + + +#include "oatpp/core/macro/codegen.hpp" +#include "oatpp/core/Types.hpp" + +namespace org::openapitools::client::model +{ + +/* Begin DTO code-generation */ +#include OATPP_CODEGEN_BEGIN(DTO) + +/** + * Message Data-Transfer-Object + */ +class Tag : public oatpp::DTO { + + DTO_INIT(Tag, DTO /* Extends */) + + DTO_FIELD(oatpp::Int64, id); + DTO_FIELD(oatpp::Boolean, idIsSet); + DTO_FIELD(oatpp::String, name); + DTO_FIELD(oatpp::Boolean, nameIsSet); + +}; + +/* End DTO code-generation */ +#include OATPP_CODEGEN_END(DTO) + + +} // namespace org::openapitools::client::model + +#endif /* Tag_H_ */ diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp index 8fbef0fb8c5c..e69de29bb2d1 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp @@ -1,160 +0,0 @@ -/** - * OpenAPI Petstore - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - * https://openapi-generator.tech - * Do not edit the class manually. - */ - -#include "PFXApiResponse.h" - -#include -#include -#include -#include - -#include "PFXHelpers.h" - -namespace test_namespace { - -PFXApiResponse::PFXApiResponse(QString json) { - this->initializeModel(); - this->fromJson(json); -} - -PFXApiResponse::PFXApiResponse() { - this->initializeModel(); -} - -PFXApiResponse::~PFXApiResponse() {} - -void PFXApiResponse::initializeModel() { - - m_code_isSet = false; - m_code_isValid = false; - - m_type_isSet = false; - m_type_isValid = false; - - m_message_isSet = false; - m_message_isValid = false; -} - -void PFXApiResponse::fromJson(QString jsonString) { - QByteArray array(jsonString.toStdString().c_str()); - QJsonDocument doc = QJsonDocument::fromJson(array); - QJsonObject jsonObject = doc.object(); - this->fromJsonObject(jsonObject); -} - -void PFXApiResponse::fromJsonObject(QJsonObject json) { - - m_code_isValid = ::test_namespace::fromJsonValue(m_code, json[QString("code")]); - m_code_isSet = !json[QString("code")].isNull() && m_code_isValid; - - m_type_isValid = ::test_namespace::fromJsonValue(m_type, json[QString("type")]); - m_type_isSet = !json[QString("type")].isNull() && m_type_isValid; - - m_message_isValid = ::test_namespace::fromJsonValue(m_message, json[QString("message")]); - m_message_isSet = !json[QString("message")].isNull() && m_message_isValid; -} - -QString PFXApiResponse::asJson() const { - QJsonObject obj = this->asJsonObject(); - QJsonDocument doc(obj); - QByteArray bytes = doc.toJson(); - return QString(bytes); -} - -QJsonObject PFXApiResponse::asJsonObject() const { - QJsonObject obj; - if (m_code_isSet) { - obj.insert(QString("code"), ::test_namespace::toJsonValue(m_code)); - } - if (m_type_isSet) { - obj.insert(QString("type"), ::test_namespace::toJsonValue(m_type)); - } - if (m_message_isSet) { - obj.insert(QString("message"), ::test_namespace::toJsonValue(m_message)); - } - return obj; -} - -qint32 PFXApiResponse::getCode() const { - return m_code; -} -void PFXApiResponse::setCode(const qint32 &code) { - m_code = code; - m_code_isSet = true; -} - -bool PFXApiResponse::is_code_Set() const{ - return m_code_isSet; -} - -bool PFXApiResponse::is_code_Valid() const{ - return m_code_isValid; -} - -QString PFXApiResponse::getType() const { - return m_type; -} -void PFXApiResponse::setType(const QString &type) { - m_type = type; - m_type_isSet = true; -} - -bool PFXApiResponse::is_type_Set() const{ - return m_type_isSet; -} - -bool PFXApiResponse::is_type_Valid() const{ - return m_type_isValid; -} - -QString PFXApiResponse::getMessage() const { - return m_message; -} -void PFXApiResponse::setMessage(const QString &message) { - m_message = message; - m_message_isSet = true; -} - -bool PFXApiResponse::is_message_Set() const{ - return m_message_isSet; -} - -bool PFXApiResponse::is_message_Valid() const{ - return m_message_isValid; -} - -bool PFXApiResponse::isSet() const { - bool isObjectUpdated = false; - do { - if (m_code_isSet) { - isObjectUpdated = true; - break; - } - - if (m_type_isSet) { - isObjectUpdated = true; - break; - } - - if (m_message_isSet) { - isObjectUpdated = true; - break; - } - } while (false); - return isObjectUpdated; -} - -bool PFXApiResponse::isValid() const { - // only required properties are required for the object to be considered valid - return true; -} - -} // namespace test_namespace diff --git a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/appsettings.json index e69de29bb2d1..def9159a7d94 100644 --- a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/appsettings.json index e69de29bb2d1..def9159a7d94 100644 --- a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Filters/BasePathFilter.cs b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Filters/BasePathFilter.cs index 97ae99c9295a..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Filters/BasePathFilter.cs +++ b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Filters/BasePathFilter.cs @@ -1,60 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.Linq; -using System.Text.RegularExpressions; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// BasePath Document Filter sets BasePath property of OpenAPI and removes it from the individual URL paths - /// - public class BasePathFilter : IDocumentFilter - { - /// - /// Constructor - /// - /// BasePath to remove from Operations - public BasePathFilter(string basePath) - { - BasePath = basePath; - } - - /// - /// Gets the BasePath of the OpenAPI Doc - /// - /// The BasePath of the OpenAPI Doc - public string BasePath { get; } - - /// - /// Apply the filter - /// - /// OpenApiDocument - /// FilterContext - public void Apply(OpenApiDocument openapiDoc, DocumentFilterContext context) - { - //openapiDoc.BasePath = BasePath; - - var pathsToModify = openapiDoc.Paths.Where(p => p.Key.StartsWith(BasePath)).ToList(); - - foreach (var (key, value) in pathsToModify) - { - if (key.StartsWith(BasePath)) - { - var newKey = Regex.Replace(key, $"^{BasePath}", string.Empty); - openapiDoc.Paths.Remove(key); - openapiDoc.Paths.Add(newKey, value); - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/appsettings.json index e69de29bb2d1..def9159a7d94 100644 --- a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/appsettings.json index e69de29bb2d1..def9159a7d94 100644 --- a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile index e69de29bb2d1..7184e1ece4d0 100644 --- a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile +++ b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile @@ -0,0 +1,32 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +# Container we use for final publish +FROM mcr.microsoft.com/dotnet/core/aspnet:6.0-buster-slim AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +# Build container +FROM mcr.microsoft.com/dotnet/core/sdk:6.0-buster AS build + +# Copy the code into the container +WORKDIR /src +COPY ["src/Org.OpenAPITools/Org.OpenAPITools.csproj", "Org.OpenAPITools/"] + +# NuGet restore +RUN dotnet restore "Org.OpenAPITools/Org.OpenAPITools.csproj" +COPY ["src/Org.OpenAPITools/", "Org.OpenAPITools/"] + +# Build the API +WORKDIR "Org.OpenAPITools" +RUN dotnet build "Org.OpenAPITools.csproj" -c Release -o /app/build + +# Publish it +FROM build AS publish +RUN dotnet publish "Org.OpenAPITools.csproj" -c Release -o /app/publish + +# Make the final image for publishing +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Org.OpenAPITools.dll"] diff --git a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/appsettings.json index e69de29bb2d1..def9159a7d94 100644 --- a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs index e69de29bb2d1..122f58cabe4a 100644 --- a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/OpenApi/TypeExtensions.cs @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.Linq; +using System.Text; + +namespace Org.OpenAPITools.OpenApi +{ + /// + /// Replacement utilities from Swashbuckle.AspNetCore.SwaggerGen which are not in 5.x + /// + public static class TypeExtensions + { + /// + /// Produce a friendly name for the type which is unique. + /// + /// + /// + public static string FriendlyId(this Type type, bool fullyQualified = false) + { + var typeName = fullyQualified + ? type.FullNameSansTypeParameters().Replace("+", ".") + : type.Name; + + if (type.IsGenericType) + { + var genericArgumentIds = type.GetGenericArguments() + .Select(t => t.FriendlyId(fullyQualified)) + .ToArray(); + + return new StringBuilder(typeName) + .Replace($"`{genericArgumentIds.Count()}", string.Empty) + .Append($"[{string.Join(",", genericArgumentIds).TrimEnd(',')}]") + .ToString(); + } + + return typeName; + } + + /// + /// Determine the fully qualified type name without type parameters. + /// + /// + public static string FullNameSansTypeParameters(this Type type) + { + var fullName = type.FullName; + if (string.IsNullOrEmpty(fullName)) + fullName = type.Name; + var chopIndex = fullName.IndexOf("[[", StringComparison.Ordinal); + return (chopIndex == -1) ? fullName : fullName.Substring(0, chopIndex); + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json index b47dce3d2c68..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json @@ -1,1203 +0,0 @@ -{ - "openapi" : "3.0.0", - "info" : { - "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", - "license" : { - "name" : "Apache-2.0", - "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" - }, - "title" : "OpenAPI Petstore", - "version" : "1.0.0" - }, - "externalDocs" : { - "description" : "Find out more about Swagger", - "url" : "http://swagger.io" - }, - "servers" : [ { - "url" : "http://petstore.swagger.io/v2" - } ], - "tags" : [ { - "description" : "Everything about your Pets", - "name" : "pet" - }, { - "description" : "Access to Petstore orders", - "name" : "store" - }, { - "description" : "Operations about user", - "name" : "user" - } ], - "paths" : { - "/test" : { - "get" : { - "parameters" : [ { - "explode" : true, - "in" : "query", - "name" : "testQuery", - "required" : false, - "schema" : { - "$ref" : "#/components/schemas/TestEnum" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "description" : "OK" - } - }, - "summary" : "Test API" - } - }, - "/pet" : { - "post" : { - "description" : "", - "operationId" : "addPet", - "requestBody" : { - "$ref" : "#/components/requestBodies/Pet" - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Add a new pet to the store", - "tags" : [ "pet" ] - }, - "put" : { - "description" : "", - "operationId" : "updatePet", - "requestBody" : { - "$ref" : "#/components/requestBodies/Pet" - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Pet not found" - }, - "405" : { - "description" : "Validation exception" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Update an existing pet", - "tags" : [ "pet" ] - } - }, - "/pet/findByStatus" : { - "get" : { - "description" : "Multiple status values can be provided with comma separated strings", - "operationId" : "findPetsByStatus", - "parameters" : [ { - "deprecated" : true, - "description" : "Status values that need to be considered for filter", - "explode" : false, - "in" : "query", - "name" : "status", - "required" : true, - "schema" : { - "items" : { - "default" : "available", - "enum" : [ "available", "pending", "sold" ], - "type" : "string" - }, - "type" : "array" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - }, - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid status value" - } - }, - "security" : [ { - "petstore_auth" : [ "read:pets" ] - } ], - "summary" : "Finds Pets by status", - "tags" : [ "pet" ] - } - }, - "/pet/findByTags" : { - "get" : { - "deprecated" : true, - "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", - "operationId" : "findPetsByTags", - "parameters" : [ { - "description" : "Tags to filter by", - "explode" : false, - "in" : "query", - "name" : "tags", - "required" : true, - "schema" : { - "items" : { - "type" : "string" - }, - "type" : "array" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - }, - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid tag value" - } - }, - "security" : [ { - "petstore_auth" : [ "read:pets" ] - } ], - "summary" : "Finds Pets by tags", - "tags" : [ "pet" ] - } - }, - "/pet/{petId}" : { - "delete" : { - "description" : "", - "operationId" : "deletePet", - "parameters" : [ { - "explode" : false, - "in" : "header", - "name" : "api_key", - "required" : false, - "schema" : { - "type" : "string" - }, - "style" : "simple" - }, { - "description" : "Pet id to delete", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "responses" : { - "400" : { - "description" : "Invalid pet value" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Deletes a pet", - "tags" : [ "pet" ] - }, - "get" : { - "description" : "Returns a single pet", - "operationId" : "getPetById", - "parameters" : [ { - "description" : "ID of pet to return", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Pet not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Find pet by ID", - "tags" : [ "pet" ] - }, - "post" : { - "description" : "", - "operationId" : "updatePetWithForm", - "parameters" : [ { - "description" : "ID of pet that needs to be updated", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "requestBody" : { - "content" : { - "application/x-www-form-urlencoded" : { - "schema" : { - "$ref" : "#/components/schemas/updatePetWithForm_request" - } - } - } - }, - "responses" : { - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Updates a pet in the store with form data", - "tags" : [ "pet" ] - } - }, - "/pet/{petId}/uploadImage" : { - "post" : { - "description" : "", - "operationId" : "uploadFile", - "parameters" : [ { - "description" : "ID of pet to update", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "requestBody" : { - "content" : { - "multipart/form-data" : { - "schema" : { - "$ref" : "#/components/schemas/uploadFile_request" - } - } - } - }, - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ApiResponse" - } - } - }, - "description" : "successful operation" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "uploads an image", - "tags" : [ "pet" ] - } - }, - "/store/inventory" : { - "get" : { - "description" : "Returns a map of status codes to quantities", - "operationId" : "getInventory", - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "additionalProperties" : { - "format" : "int32", - "type" : "integer" - }, - "type" : "object" - } - } - }, - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Returns pet inventories by status", - "tags" : [ "store" ] - } - }, - "/store/order" : { - "post" : { - "description" : "", - "operationId" : "placeOrder", - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "order placed for purchasing the pet", - "required" : true - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid Order" - } - }, - "summary" : "Place an order for a pet", - "tags" : [ "store" ] - } - }, - "/store/order/{orderId}" : { - "delete" : { - "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "operationId" : "deleteOrder", - "parameters" : [ { - "description" : "ID of the order that needs to be deleted", - "explode" : false, - "in" : "path", - "name" : "orderId", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "responses" : { - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Order not found" - } - }, - "summary" : "Delete purchase order by ID", - "tags" : [ "store" ] - }, - "get" : { - "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions", - "operationId" : "getOrderById", - "parameters" : [ { - "description" : "ID of pet that needs to be fetched", - "explode" : false, - "in" : "path", - "name" : "orderId", - "required" : true, - "schema" : { - "format" : "int64", - "maximum" : 5, - "minimum" : 1, - "type" : "integer" - }, - "style" : "simple" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Order not found" - } - }, - "summary" : "Find purchase order by ID", - "tags" : [ "store" ] - } - }, - "/user" : { - "post" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "createUser", - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "Created user object", - "required" : true - }, - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Create user", - "tags" : [ "user" ] - } - }, - "/user/createWithArray" : { - "post" : { - "description" : "", - "operationId" : "createUsersWithArrayInput", - "requestBody" : { - "$ref" : "#/components/requestBodies/UserArray" - }, - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Creates list of users with given input array", - "tags" : [ "user" ] - } - }, - "/user/createWithList" : { - "post" : { - "description" : "", - "operationId" : "createUsersWithListInput", - "requestBody" : { - "$ref" : "#/components/requestBodies/UserArray" - }, - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Creates list of users with given input array", - "tags" : [ "user" ] - } - }, - "/user/login" : { - "get" : { - "description" : "", - "operationId" : "loginUser", - "parameters" : [ { - "description" : "The user name for login", - "explode" : true, - "in" : "query", - "name" : "username", - "required" : true, - "schema" : { - "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", - "type" : "string" - }, - "style" : "form" - }, { - "description" : "The password for login in clear text", - "explode" : true, - "in" : "query", - "name" : "password", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "type" : "string" - } - }, - "application/json" : { - "schema" : { - "type" : "string" - } - } - }, - "description" : "successful operation", - "headers" : { - "Set-Cookie" : { - "description" : "Cookie authentication key for use with the `api_key` apiKey authentication.", - "explode" : false, - "schema" : { - "example" : "AUTH_KEY=abcde12345; Path=/; HttpOnly", - "type" : "string" - }, - "style" : "simple" - }, - "X-Rate-Limit" : { - "description" : "calls per hour allowed by the user", - "explode" : false, - "schema" : { - "format" : "int32", - "type" : "integer" - }, - "style" : "simple" - }, - "X-Expires-After" : { - "description" : "date in UTC when token expires", - "explode" : false, - "schema" : { - "format" : "date-time", - "type" : "string" - }, - "style" : "simple" - } - } - }, - "400" : { - "description" : "Invalid username/password supplied" - } - }, - "summary" : "Logs user into the system", - "tags" : [ "user" ] - } - }, - "/user/logout" : { - "get" : { - "description" : "", - "operationId" : "logoutUser", - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Logs out current logged in user session", - "tags" : [ "user" ] - } - }, - "/user/{username}" : { - "delete" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "deleteUser", - "parameters" : [ { - "description" : "The name that needs to be deleted", - "explode" : false, - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "responses" : { - "400" : { - "description" : "Invalid username supplied" - }, - "404" : { - "description" : "User not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Delete user", - "tags" : [ "user" ] - }, - "get" : { - "description" : "", - "operationId" : "getUserByName", - "parameters" : [ { - "description" : "The name that needs to be fetched. Use user1 for testing.", - "explode" : false, - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid username supplied" - }, - "404" : { - "description" : "User not found" - } - }, - "summary" : "Get user by user name", - "tags" : [ "user" ] - }, - "put" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "updateUser", - "parameters" : [ { - "description" : "name that need to be deleted", - "explode" : false, - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "Updated user object", - "required" : true - }, - "responses" : { - "400" : { - "description" : "Invalid user supplied" - }, - "404" : { - "description" : "User not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Updated user", - "tags" : [ "user" ] - } - }, - "/fake/parameter_example_test" : { - "get" : { - "description" : "", - "operationId" : "fake_parameter_example_test", - "parameters" : [ { - "explode" : true, - "in" : "query", - "name" : "data", - "required" : true, - "schema" : { - "$ref" : "#/components/schemas/Pet" - }, - "style" : "form" - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "summary" : "fake endpoint to test parameter example (object)", - "tags" : [ "fake" ] - } - }, - "/fake/nullable_example_test" : { - "get" : { - "description" : "", - "operationId" : "fake_nullable_example_test", - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestNullable" - } - } - }, - "description" : "Successful operation" - } - }, - "summary" : "Fake endpoint to test nullable example (object)", - "tags" : [ "fake" ] - } - } - }, - "components" : { - "requestBodies" : { - "UserArray" : { - "content" : { - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/User" - }, - "type" : "array" - } - } - }, - "description" : "List of user object", - "required" : true - }, - "Pet" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "Pet object that needs to be added to the store", - "required" : true - } - }, - "schemas" : { - "TestEnum" : { - "enum" : [ "A", "B" ], - "type" : "string" - }, - "TestNullable" : { - "example" : { - "nullableName" : "nullableName", - "name" : "name" - }, - "properties" : { - "name" : { - "type" : "string" - }, - "nullableName" : { - "nullable" : true, - "type" : "string" - } - }, - "type" : "object" - }, - "Order" : { - "description" : "An order for a pets from the pet store", - "example" : { - "petId" : 6, - "quantity" : 1, - "id" : 0, - "shipDate" : "2000-01-23T04:56:07.000+00:00", - "complete" : false, - "status" : "placed" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "petId" : { - "format" : "int64", - "type" : "integer" - }, - "quantity" : { - "format" : "int32", - "type" : "integer" - }, - "shipDate" : { - "format" : "date-time", - "type" : "string" - }, - "status" : { - "description" : "Order Status", - "enum" : [ "placed", "approved", "delivered" ], - "type" : "string" - }, - "complete" : { - "default" : false, - "type" : "boolean" - } - }, - "title" : "Pet Order", - "type" : "object", - "xml" : { - "name" : "Order" - } - }, - "Category" : { - "description" : "A category for a pet", - "example" : { - "name" : "name", - "id" : 6 - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "name" : { - "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", - "type" : "string" - } - }, - "title" : "Pet category", - "type" : "object", - "xml" : { - "name" : "Category" - } - }, - "User" : { - "description" : "A User who is purchasing from the pet store", - "example" : { - "firstName" : "firstName", - "lastName" : "lastName", - "password" : "password", - "userStatus" : 6, - "phone" : "phone", - "id" : 0, - "email" : "email", - "username" : "username" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "username" : { - "type" : "string" - }, - "firstName" : { - "type" : "string" - }, - "lastName" : { - "type" : "string" - }, - "email" : { - "type" : "string" - }, - "password" : { - "type" : "string" - }, - "phone" : { - "type" : "string" - }, - "userStatus" : { - "description" : "User Status", - "format" : "int32", - "type" : "integer" - } - }, - "title" : "a User", - "type" : "object", - "xml" : { - "name" : "User" - } - }, - "Tag" : { - "description" : "A tag for a pet", - "example" : { - "name" : "name", - "id" : 1 - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "name" : { - "type" : "string" - } - }, - "title" : "Pet Tag", - "type" : "object", - "xml" : { - "name" : "Tag" - } - }, - "Pet" : { - "description" : "A pet for sale in the pet store", - "example" : { - "photoUrls" : [ "photoUrls", "photoUrls" ], - "name" : "doggie", - "id" : 0, - "category" : { - "name" : "name", - "id" : 6 - }, - "tags" : [ { - "name" : "name", - "id" : 1 - }, { - "name" : "name", - "id" : 1 - } ], - "status" : "available" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "category" : { - "$ref" : "#/components/schemas/Category" - }, - "name" : { - "example" : "doggie", - "type" : "string" - }, - "photoUrls" : { - "items" : { - "type" : "string" - }, - "type" : "array", - "xml" : { - "name" : "photoUrl", - "wrapped" : true - } - }, - "tags" : { - "items" : { - "$ref" : "#/components/schemas/Tag" - }, - "type" : "array", - "xml" : { - "name" : "tag", - "wrapped" : true - } - }, - "status" : { - "deprecated" : true, - "description" : "pet status in the store", - "enum" : [ "available", "pending", "sold" ], - "type" : "string" - } - }, - "required" : [ "name", "photoUrls" ], - "title" : "a Pet", - "type" : "object", - "xml" : { - "name" : "Pet" - } - }, - "ApiResponse" : { - "description" : "Describes the result of uploading an image resource", - "example" : { - "code" : 0, - "type" : "type", - "message" : "message" - }, - "properties" : { - "code" : { - "format" : "int32", - "type" : "integer" - }, - "type" : { - "type" : "string" - }, - "message" : { - "type" : "string" - } - }, - "title" : "An uploaded response", - "type" : "object" - }, - "Dog" : { - "allOf" : [ { - "$ref" : "#/components/schemas/Animal" - }, { - "properties" : { - "breed" : { - "type" : "string" - } - }, - "type" : "object" - } ] - }, - "Cat" : { - "allOf" : [ { - "$ref" : "#/components/schemas/Animal" - }, { - "properties" : { - "declawed" : { - "type" : "boolean" - } - }, - "type" : "object" - } ] - }, - "Animal" : { - "discriminator" : { - "mapping" : { - "DOG" : "#/components/schemas/Dog", - "CAT" : "#/components/schemas/Cat" - }, - "propertyName" : "className" - }, - "properties" : { - "className" : { - "type" : "string" - }, - "color" : { - "default" : "red", - "type" : "string" - } - }, - "required" : [ "className" ], - "type" : "object" - }, - "updatePetWithForm_request" : { - "properties" : { - "name" : { - "description" : "Updated name of the pet", - "type" : "string" - }, - "status" : { - "description" : "Updated status of the pet", - "type" : "string" - } - }, - "type" : "object" - }, - "uploadFile_request" : { - "properties" : { - "additionalMetadata" : { - "description" : "Additional data to pass to server", - "type" : "string" - }, - "file" : { - "description" : "file to upload", - "format" : "binary", - "type" : "string" - } - }, - "type" : "object" - } - }, - "securitySchemes" : { - "petstore_auth" : { - "flows" : { - "implicit" : { - "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", - "scopes" : { - "write:pets" : "modify pets in your account", - "read:pets" : "read your pets" - } - } - }, - "type" : "oauth2" - }, - "api_key" : { - "in" : "header", - "name" : "api_key", - "type" : "apiKey" - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs index e69de29bb2d1..18796da30fcb 100644 --- a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs +++ b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs @@ -0,0 +1,45 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.Formatters; + +namespace Org.OpenAPITools.Formatters +{ + /// + public class InputFormatterStream : InputFormatter + { + /// + public InputFormatterStream() + { + SupportedMediaTypes.Add("application/octet-stream"); + SupportedMediaTypes.Add("image/jpeg"); + } + + /// + public override Task ReadRequestBodyAsync(InputFormatterContext context) + { + return InputFormatterResult.SuccessAsync(context.HttpContext.Request.Body); + } + + /// + protected override bool CanReadType(Type type) + { + if (type == typeof(Stream)) + { + return true; + } + + return false; + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec index e69de29bb2d1..b1d83a359618 100644 --- a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec +++ b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec @@ -0,0 +1,20 @@ + + + + $id$ + 1.0.0 + OpenAPI Library + OpenAPI + OpenAPI + https://www.apache.org/licenses/LICENSE-2.0.html + + false + A library generated from a OpenAPI doc + Summary of changes made in this release of the package. + No Copyright + Org.OpenAPITools + + diff --git a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/appsettings.json index e69de29bb2d1..def9159a7d94 100644 --- a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Dockerfile b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Dockerfile index e69de29bb2d1..c24f45dbc5a4 100644 --- a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Dockerfile +++ b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Dockerfile @@ -0,0 +1,32 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +# Container we use for final publish +FROM mcr.microsoft.com/dotnet/core/aspnet:8.0-buster-slim AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +# Build container +FROM mcr.microsoft.com/dotnet/core/sdk:8.0-buster AS build + +# Copy the code into the container +WORKDIR /src +COPY ["src/Org.OpenAPITools/Org.OpenAPITools.csproj", "Org.OpenAPITools/"] + +# NuGet restore +RUN dotnet restore "Org.OpenAPITools/Org.OpenAPITools.csproj" +COPY ["src/Org.OpenAPITools/", "Org.OpenAPITools/"] + +# Build the API +WORKDIR "Org.OpenAPITools" +RUN dotnet build "Org.OpenAPITools.csproj" -c Release -o /app/build + +# Publish it +FROM build AS publish +RUN dotnet publish "Org.OpenAPITools.csproj" -c Release -o /app/publish + +# Make the final image for publishing +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Org.OpenAPITools.dll"] diff --git a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Startup.cs b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Startup.cs index e69de29bb2d1..bf30e991889e 100644 --- a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Startup.cs +++ b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Startup.cs @@ -0,0 +1,150 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.IO; +using System.Reflection; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.OpenApi.Models; +using System.Text.Json; +using System.Text.Json.Serialization; +using Org.OpenAPITools.Authentication; +using Org.OpenAPITools.Filters; +using Org.OpenAPITools.OpenApi; +using Org.OpenAPITools.Formatters; + +namespace Org.OpenAPITools +{ + /// + /// Startup + /// + public class Startup + { + /// + /// Constructor + /// + /// + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + /// + /// The application configuration. + /// + public IConfiguration Configuration { get; } + + /// + /// This method gets called by the runtime. Use this method to add services to the container. + /// + /// + public void ConfigureServices(IServiceCollection services) + { + services.AddTransient(); + services.AddAuthorization(authConfig => + { + authConfig.AddPolicy("api_key", policyBuilder => + { + policyBuilder + .AddRequirements(new ApiKeyRequirement(new[] { "my-secret-key" },"api_key")); + }); + }); + + // Add framework services. + services + // Don't need the full MVC stack for an API, see https://andrewlock.net/comparing-startup-between-the-asp-net-core-3-templates/ + .AddControllers(options => { + options.InputFormatters.Insert(0, new InputFormatterStream()); + }) + .AddJsonOptions(options => + { + options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); + }); + services + .AddSwaggerGen(c => + { + c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true); + + c.SwaggerDoc("1.0.0", new OpenApiInfo + { + Title = "OpenAPI Petstore", + Description = "OpenAPI Petstore (ASP.NET Core 8.0)", + TermsOfService = new Uri("https://github.com/openapitools/openapi-generator"), + Contact = new OpenApiContact + { + Name = "OpenAPI-Generator Contributors", + Url = new Uri("https://github.com/openapitools/openapi-generator"), + Email = "" + }, + License = new OpenApiLicense + { + Name = "NoLicense", + Url = new Uri("https://www.apache.org/licenses/LICENSE-2.0.html") + }, + Version = "1.0.0", + }); + c.CustomSchemaIds(type => type.FriendlyId(true)); + c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{Assembly.GetExecutingAssembly().GetName().Name}.xml"); + // Sets the basePath property in the OpenAPI document generated + c.DocumentFilter("/v2"); + + // Include DataAnnotation attributes on Controller Action parameters as OpenAPI validation rules (e.g required, pattern, ..) + // Use [ValidateModelState] on Actions to actually validate it in C# as well! + c.OperationFilter(); + }); + } + + /// + /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + /// + /// + /// + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseHsts(); + } + + app.UseHttpsRedirection(); + app.UseDefaultFiles(); + app.UseStaticFiles(); + app.UseSwagger(c => + { + c.RouteTemplate = "openapi/{documentName}/openapi.json"; + }) + .UseSwaggerUI(c => + { + // set route prefix to openapi, e.g. http://localhost:8080/openapi/index.html + c.RoutePrefix = "openapi"; + //TODO: Either use the SwaggerGen generated OpenAPI contract (generated from C# classes) + c.SwaggerEndpoint("/openapi/1.0.0/openapi.json", "OpenAPI Petstore"); + + //TODO: Or alternatively use the original OpenAPI contract that's included in the static files + // c.SwaggerEndpoint("/openapi-original.json", "OpenAPI Petstore Original"); + }); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapControllers(); + }); + } + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile index e69de29bb2d1..c24f45dbc5a4 100644 --- a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile +++ b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Dockerfile @@ -0,0 +1,32 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +# Container we use for final publish +FROM mcr.microsoft.com/dotnet/core/aspnet:8.0-buster-slim AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +# Build container +FROM mcr.microsoft.com/dotnet/core/sdk:8.0-buster AS build + +# Copy the code into the container +WORKDIR /src +COPY ["src/Org.OpenAPITools/Org.OpenAPITools.csproj", "Org.OpenAPITools/"] + +# NuGet restore +RUN dotnet restore "Org.OpenAPITools/Org.OpenAPITools.csproj" +COPY ["src/Org.OpenAPITools/", "Org.OpenAPITools/"] + +# Build the API +WORKDIR "Org.OpenAPITools" +RUN dotnet build "Org.OpenAPITools.csproj" -c Release -o /app/build + +# Publish it +FROM build AS publish +RUN dotnet publish "Org.OpenAPITools.csproj" -c Release -o /app/publish + +# Make the final image for publishing +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Org.OpenAPITools.dll"] diff --git a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/appsettings.json index e69de29bb2d1..def9159a7d94 100644 --- a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/wwwroot/openapi-original.json index b47dce3d2c68..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/wwwroot/openapi-original.json +++ b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/wwwroot/openapi-original.json @@ -1,1203 +0,0 @@ -{ - "openapi" : "3.0.0", - "info" : { - "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", - "license" : { - "name" : "Apache-2.0", - "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" - }, - "title" : "OpenAPI Petstore", - "version" : "1.0.0" - }, - "externalDocs" : { - "description" : "Find out more about Swagger", - "url" : "http://swagger.io" - }, - "servers" : [ { - "url" : "http://petstore.swagger.io/v2" - } ], - "tags" : [ { - "description" : "Everything about your Pets", - "name" : "pet" - }, { - "description" : "Access to Petstore orders", - "name" : "store" - }, { - "description" : "Operations about user", - "name" : "user" - } ], - "paths" : { - "/test" : { - "get" : { - "parameters" : [ { - "explode" : true, - "in" : "query", - "name" : "testQuery", - "required" : false, - "schema" : { - "$ref" : "#/components/schemas/TestEnum" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "description" : "OK" - } - }, - "summary" : "Test API" - } - }, - "/pet" : { - "post" : { - "description" : "", - "operationId" : "addPet", - "requestBody" : { - "$ref" : "#/components/requestBodies/Pet" - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Add a new pet to the store", - "tags" : [ "pet" ] - }, - "put" : { - "description" : "", - "operationId" : "updatePet", - "requestBody" : { - "$ref" : "#/components/requestBodies/Pet" - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Pet not found" - }, - "405" : { - "description" : "Validation exception" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Update an existing pet", - "tags" : [ "pet" ] - } - }, - "/pet/findByStatus" : { - "get" : { - "description" : "Multiple status values can be provided with comma separated strings", - "operationId" : "findPetsByStatus", - "parameters" : [ { - "deprecated" : true, - "description" : "Status values that need to be considered for filter", - "explode" : false, - "in" : "query", - "name" : "status", - "required" : true, - "schema" : { - "items" : { - "default" : "available", - "enum" : [ "available", "pending", "sold" ], - "type" : "string" - }, - "type" : "array" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - }, - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid status value" - } - }, - "security" : [ { - "petstore_auth" : [ "read:pets" ] - } ], - "summary" : "Finds Pets by status", - "tags" : [ "pet" ] - } - }, - "/pet/findByTags" : { - "get" : { - "deprecated" : true, - "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", - "operationId" : "findPetsByTags", - "parameters" : [ { - "description" : "Tags to filter by", - "explode" : false, - "in" : "query", - "name" : "tags", - "required" : true, - "schema" : { - "items" : { - "type" : "string" - }, - "type" : "array" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - }, - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid tag value" - } - }, - "security" : [ { - "petstore_auth" : [ "read:pets" ] - } ], - "summary" : "Finds Pets by tags", - "tags" : [ "pet" ] - } - }, - "/pet/{petId}" : { - "delete" : { - "description" : "", - "operationId" : "deletePet", - "parameters" : [ { - "explode" : false, - "in" : "header", - "name" : "api_key", - "required" : false, - "schema" : { - "type" : "string" - }, - "style" : "simple" - }, { - "description" : "Pet id to delete", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "responses" : { - "400" : { - "description" : "Invalid pet value" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Deletes a pet", - "tags" : [ "pet" ] - }, - "get" : { - "description" : "Returns a single pet", - "operationId" : "getPetById", - "parameters" : [ { - "description" : "ID of pet to return", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Pet not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Find pet by ID", - "tags" : [ "pet" ] - }, - "post" : { - "description" : "", - "operationId" : "updatePetWithForm", - "parameters" : [ { - "description" : "ID of pet that needs to be updated", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "requestBody" : { - "content" : { - "application/x-www-form-urlencoded" : { - "schema" : { - "$ref" : "#/components/schemas/updatePetWithForm_request" - } - } - } - }, - "responses" : { - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Updates a pet in the store with form data", - "tags" : [ "pet" ] - } - }, - "/pet/{petId}/uploadImage" : { - "post" : { - "description" : "", - "operationId" : "uploadFile", - "parameters" : [ { - "description" : "ID of pet to update", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "requestBody" : { - "content" : { - "multipart/form-data" : { - "schema" : { - "$ref" : "#/components/schemas/uploadFile_request" - } - } - } - }, - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ApiResponse" - } - } - }, - "description" : "successful operation" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "uploads an image", - "tags" : [ "pet" ] - } - }, - "/store/inventory" : { - "get" : { - "description" : "Returns a map of status codes to quantities", - "operationId" : "getInventory", - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "additionalProperties" : { - "format" : "int32", - "type" : "integer" - }, - "type" : "object" - } - } - }, - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Returns pet inventories by status", - "tags" : [ "store" ] - } - }, - "/store/order" : { - "post" : { - "description" : "", - "operationId" : "placeOrder", - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "order placed for purchasing the pet", - "required" : true - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid Order" - } - }, - "summary" : "Place an order for a pet", - "tags" : [ "store" ] - } - }, - "/store/order/{orderId}" : { - "delete" : { - "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "operationId" : "deleteOrder", - "parameters" : [ { - "description" : "ID of the order that needs to be deleted", - "explode" : false, - "in" : "path", - "name" : "orderId", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "responses" : { - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Order not found" - } - }, - "summary" : "Delete purchase order by ID", - "tags" : [ "store" ] - }, - "get" : { - "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions", - "operationId" : "getOrderById", - "parameters" : [ { - "description" : "ID of pet that needs to be fetched", - "explode" : false, - "in" : "path", - "name" : "orderId", - "required" : true, - "schema" : { - "format" : "int64", - "maximum" : 5, - "minimum" : 1, - "type" : "integer" - }, - "style" : "simple" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Order not found" - } - }, - "summary" : "Find purchase order by ID", - "tags" : [ "store" ] - } - }, - "/user" : { - "post" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "createUser", - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "Created user object", - "required" : true - }, - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Create user", - "tags" : [ "user" ] - } - }, - "/user/createWithArray" : { - "post" : { - "description" : "", - "operationId" : "createUsersWithArrayInput", - "requestBody" : { - "$ref" : "#/components/requestBodies/UserArray" - }, - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Creates list of users with given input array", - "tags" : [ "user" ] - } - }, - "/user/createWithList" : { - "post" : { - "description" : "", - "operationId" : "createUsersWithListInput", - "requestBody" : { - "$ref" : "#/components/requestBodies/UserArray" - }, - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Creates list of users with given input array", - "tags" : [ "user" ] - } - }, - "/user/login" : { - "get" : { - "description" : "", - "operationId" : "loginUser", - "parameters" : [ { - "description" : "The user name for login", - "explode" : true, - "in" : "query", - "name" : "username", - "required" : true, - "schema" : { - "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", - "type" : "string" - }, - "style" : "form" - }, { - "description" : "The password for login in clear text", - "explode" : true, - "in" : "query", - "name" : "password", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "type" : "string" - } - }, - "application/json" : { - "schema" : { - "type" : "string" - } - } - }, - "description" : "successful operation", - "headers" : { - "Set-Cookie" : { - "description" : "Cookie authentication key for use with the `api_key` apiKey authentication.", - "explode" : false, - "schema" : { - "example" : "AUTH_KEY=abcde12345; Path=/; HttpOnly", - "type" : "string" - }, - "style" : "simple" - }, - "X-Rate-Limit" : { - "description" : "calls per hour allowed by the user", - "explode" : false, - "schema" : { - "format" : "int32", - "type" : "integer" - }, - "style" : "simple" - }, - "X-Expires-After" : { - "description" : "date in UTC when token expires", - "explode" : false, - "schema" : { - "format" : "date-time", - "type" : "string" - }, - "style" : "simple" - } - } - }, - "400" : { - "description" : "Invalid username/password supplied" - } - }, - "summary" : "Logs user into the system", - "tags" : [ "user" ] - } - }, - "/user/logout" : { - "get" : { - "description" : "", - "operationId" : "logoutUser", - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Logs out current logged in user session", - "tags" : [ "user" ] - } - }, - "/user/{username}" : { - "delete" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "deleteUser", - "parameters" : [ { - "description" : "The name that needs to be deleted", - "explode" : false, - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "responses" : { - "400" : { - "description" : "Invalid username supplied" - }, - "404" : { - "description" : "User not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Delete user", - "tags" : [ "user" ] - }, - "get" : { - "description" : "", - "operationId" : "getUserByName", - "parameters" : [ { - "description" : "The name that needs to be fetched. Use user1 for testing.", - "explode" : false, - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid username supplied" - }, - "404" : { - "description" : "User not found" - } - }, - "summary" : "Get user by user name", - "tags" : [ "user" ] - }, - "put" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "updateUser", - "parameters" : [ { - "description" : "name that need to be deleted", - "explode" : false, - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "Updated user object", - "required" : true - }, - "responses" : { - "400" : { - "description" : "Invalid user supplied" - }, - "404" : { - "description" : "User not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Updated user", - "tags" : [ "user" ] - } - }, - "/fake/parameter_example_test" : { - "get" : { - "description" : "", - "operationId" : "fake_parameter_example_test", - "parameters" : [ { - "explode" : true, - "in" : "query", - "name" : "data", - "required" : true, - "schema" : { - "$ref" : "#/components/schemas/Pet" - }, - "style" : "form" - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "summary" : "fake endpoint to test parameter example (object)", - "tags" : [ "fake" ] - } - }, - "/fake/nullable_example_test" : { - "get" : { - "description" : "", - "operationId" : "fake_nullable_example_test", - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestNullable" - } - } - }, - "description" : "Successful operation" - } - }, - "summary" : "Fake endpoint to test nullable example (object)", - "tags" : [ "fake" ] - } - } - }, - "components" : { - "requestBodies" : { - "UserArray" : { - "content" : { - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/User" - }, - "type" : "array" - } - } - }, - "description" : "List of user object", - "required" : true - }, - "Pet" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "Pet object that needs to be added to the store", - "required" : true - } - }, - "schemas" : { - "TestEnum" : { - "enum" : [ "A", "B" ], - "type" : "string" - }, - "TestNullable" : { - "example" : { - "nullableName" : "nullableName", - "name" : "name" - }, - "properties" : { - "name" : { - "type" : "string" - }, - "nullableName" : { - "nullable" : true, - "type" : "string" - } - }, - "type" : "object" - }, - "Order" : { - "description" : "An order for a pets from the pet store", - "example" : { - "petId" : 6, - "quantity" : 1, - "id" : 0, - "shipDate" : "2000-01-23T04:56:07.000+00:00", - "complete" : false, - "status" : "placed" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "petId" : { - "format" : "int64", - "type" : "integer" - }, - "quantity" : { - "format" : "int32", - "type" : "integer" - }, - "shipDate" : { - "format" : "date-time", - "type" : "string" - }, - "status" : { - "description" : "Order Status", - "enum" : [ "placed", "approved", "delivered" ], - "type" : "string" - }, - "complete" : { - "default" : false, - "type" : "boolean" - } - }, - "title" : "Pet Order", - "type" : "object", - "xml" : { - "name" : "Order" - } - }, - "Category" : { - "description" : "A category for a pet", - "example" : { - "name" : "name", - "id" : 6 - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "name" : { - "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", - "type" : "string" - } - }, - "title" : "Pet category", - "type" : "object", - "xml" : { - "name" : "Category" - } - }, - "User" : { - "description" : "A User who is purchasing from the pet store", - "example" : { - "firstName" : "firstName", - "lastName" : "lastName", - "password" : "password", - "userStatus" : 6, - "phone" : "phone", - "id" : 0, - "email" : "email", - "username" : "username" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "username" : { - "type" : "string" - }, - "firstName" : { - "type" : "string" - }, - "lastName" : { - "type" : "string" - }, - "email" : { - "type" : "string" - }, - "password" : { - "type" : "string" - }, - "phone" : { - "type" : "string" - }, - "userStatus" : { - "description" : "User Status", - "format" : "int32", - "type" : "integer" - } - }, - "title" : "a User", - "type" : "object", - "xml" : { - "name" : "User" - } - }, - "Tag" : { - "description" : "A tag for a pet", - "example" : { - "name" : "name", - "id" : 1 - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "name" : { - "type" : "string" - } - }, - "title" : "Pet Tag", - "type" : "object", - "xml" : { - "name" : "Tag" - } - }, - "Pet" : { - "description" : "A pet for sale in the pet store", - "example" : { - "photoUrls" : [ "photoUrls", "photoUrls" ], - "name" : "doggie", - "id" : 0, - "category" : { - "name" : "name", - "id" : 6 - }, - "tags" : [ { - "name" : "name", - "id" : 1 - }, { - "name" : "name", - "id" : 1 - } ], - "status" : "available" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "category" : { - "$ref" : "#/components/schemas/Category" - }, - "name" : { - "example" : "doggie", - "type" : "string" - }, - "photoUrls" : { - "items" : { - "type" : "string" - }, - "type" : "array", - "xml" : { - "name" : "photoUrl", - "wrapped" : true - } - }, - "tags" : { - "items" : { - "$ref" : "#/components/schemas/Tag" - }, - "type" : "array", - "xml" : { - "name" : "tag", - "wrapped" : true - } - }, - "status" : { - "deprecated" : true, - "description" : "pet status in the store", - "enum" : [ "available", "pending", "sold" ], - "type" : "string" - } - }, - "required" : [ "name", "photoUrls" ], - "title" : "a Pet", - "type" : "object", - "xml" : { - "name" : "Pet" - } - }, - "ApiResponse" : { - "description" : "Describes the result of uploading an image resource", - "example" : { - "code" : 0, - "type" : "type", - "message" : "message" - }, - "properties" : { - "code" : { - "format" : "int32", - "type" : "integer" - }, - "type" : { - "type" : "string" - }, - "message" : { - "type" : "string" - } - }, - "title" : "An uploaded response", - "type" : "object" - }, - "Dog" : { - "allOf" : [ { - "$ref" : "#/components/schemas/Animal" - }, { - "properties" : { - "breed" : { - "type" : "string" - } - }, - "type" : "object" - } ] - }, - "Cat" : { - "allOf" : [ { - "$ref" : "#/components/schemas/Animal" - }, { - "properties" : { - "declawed" : { - "type" : "boolean" - } - }, - "type" : "object" - } ] - }, - "Animal" : { - "discriminator" : { - "mapping" : { - "DOG" : "#/components/schemas/Dog", - "CAT" : "#/components/schemas/Cat" - }, - "propertyName" : "className" - }, - "properties" : { - "className" : { - "type" : "string" - }, - "color" : { - "default" : "red", - "type" : "string" - } - }, - "required" : [ "className" ], - "type" : "object" - }, - "updatePetWithForm_request" : { - "properties" : { - "name" : { - "description" : "Updated name of the pet", - "type" : "string" - }, - "status" : { - "description" : "Updated status of the pet", - "type" : "string" - } - }, - "type" : "object" - }, - "uploadFile_request" : { - "properties" : { - "additionalMetadata" : { - "description" : "Additional data to pass to server", - "type" : "string" - }, - "file" : { - "description" : "file to upload", - "format" : "binary", - "type" : "string" - } - }, - "type" : "object" - } - }, - "securitySchemes" : { - "petstore_auth" : { - "flows" : { - "implicit" : { - "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", - "scopes" : { - "write:pets" : "modify pets in your account", - "read:pets" : "read your pets" - } - } - }, - "type" : "oauth2" - }, - "api_key" : { - "in" : "header", - "name" : "api_key", - "type" : "apiKey" - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj index e69de29bb2d1..99b5e849d995 100644 --- a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,27 @@ + + + A library generated from a OpenAPI doc + No Copyright + OpenAPI + net8.0 + true + true + 1.0.0 + Org.OpenAPITools + Org.OpenAPITools + cb87e868-8646-48ef-9bb6-344b537d0d37 + Linux + ..\.. + + + + + + + + + + + + + diff --git a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json index b47dce3d2c68..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json +++ b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json @@ -1,1203 +0,0 @@ -{ - "openapi" : "3.0.0", - "info" : { - "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", - "license" : { - "name" : "Apache-2.0", - "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" - }, - "title" : "OpenAPI Petstore", - "version" : "1.0.0" - }, - "externalDocs" : { - "description" : "Find out more about Swagger", - "url" : "http://swagger.io" - }, - "servers" : [ { - "url" : "http://petstore.swagger.io/v2" - } ], - "tags" : [ { - "description" : "Everything about your Pets", - "name" : "pet" - }, { - "description" : "Access to Petstore orders", - "name" : "store" - }, { - "description" : "Operations about user", - "name" : "user" - } ], - "paths" : { - "/test" : { - "get" : { - "parameters" : [ { - "explode" : true, - "in" : "query", - "name" : "testQuery", - "required" : false, - "schema" : { - "$ref" : "#/components/schemas/TestEnum" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "description" : "OK" - } - }, - "summary" : "Test API" - } - }, - "/pet" : { - "post" : { - "description" : "", - "operationId" : "addPet", - "requestBody" : { - "$ref" : "#/components/requestBodies/Pet" - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Add a new pet to the store", - "tags" : [ "pet" ] - }, - "put" : { - "description" : "", - "operationId" : "updatePet", - "requestBody" : { - "$ref" : "#/components/requestBodies/Pet" - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Pet not found" - }, - "405" : { - "description" : "Validation exception" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Update an existing pet", - "tags" : [ "pet" ] - } - }, - "/pet/findByStatus" : { - "get" : { - "description" : "Multiple status values can be provided with comma separated strings", - "operationId" : "findPetsByStatus", - "parameters" : [ { - "deprecated" : true, - "description" : "Status values that need to be considered for filter", - "explode" : false, - "in" : "query", - "name" : "status", - "required" : true, - "schema" : { - "items" : { - "default" : "available", - "enum" : [ "available", "pending", "sold" ], - "type" : "string" - }, - "type" : "array" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - }, - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid status value" - } - }, - "security" : [ { - "petstore_auth" : [ "read:pets" ] - } ], - "summary" : "Finds Pets by status", - "tags" : [ "pet" ] - } - }, - "/pet/findByTags" : { - "get" : { - "deprecated" : true, - "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", - "operationId" : "findPetsByTags", - "parameters" : [ { - "description" : "Tags to filter by", - "explode" : false, - "in" : "query", - "name" : "tags", - "required" : true, - "schema" : { - "items" : { - "type" : "string" - }, - "type" : "array" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - }, - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid tag value" - } - }, - "security" : [ { - "petstore_auth" : [ "read:pets" ] - } ], - "summary" : "Finds Pets by tags", - "tags" : [ "pet" ] - } - }, - "/pet/{petId}" : { - "delete" : { - "description" : "", - "operationId" : "deletePet", - "parameters" : [ { - "explode" : false, - "in" : "header", - "name" : "api_key", - "required" : false, - "schema" : { - "type" : "string" - }, - "style" : "simple" - }, { - "description" : "Pet id to delete", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "responses" : { - "400" : { - "description" : "Invalid pet value" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Deletes a pet", - "tags" : [ "pet" ] - }, - "get" : { - "description" : "Returns a single pet", - "operationId" : "getPetById", - "parameters" : [ { - "description" : "ID of pet to return", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Pet not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Find pet by ID", - "tags" : [ "pet" ] - }, - "post" : { - "description" : "", - "operationId" : "updatePetWithForm", - "parameters" : [ { - "description" : "ID of pet that needs to be updated", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "requestBody" : { - "content" : { - "application/x-www-form-urlencoded" : { - "schema" : { - "$ref" : "#/components/schemas/updatePetWithForm_request" - } - } - } - }, - "responses" : { - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Updates a pet in the store with form data", - "tags" : [ "pet" ] - } - }, - "/pet/{petId}/uploadImage" : { - "post" : { - "description" : "", - "operationId" : "uploadFile", - "parameters" : [ { - "description" : "ID of pet to update", - "explode" : false, - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - }, - "style" : "simple" - } ], - "requestBody" : { - "content" : { - "multipart/form-data" : { - "schema" : { - "$ref" : "#/components/schemas/uploadFile_request" - } - } - } - }, - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ApiResponse" - } - } - }, - "description" : "successful operation" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "uploads an image", - "tags" : [ "pet" ] - } - }, - "/store/inventory" : { - "get" : { - "description" : "Returns a map of status codes to quantities", - "operationId" : "getInventory", - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "additionalProperties" : { - "format" : "int32", - "type" : "integer" - }, - "type" : "object" - } - } - }, - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Returns pet inventories by status", - "tags" : [ "store" ] - } - }, - "/store/order" : { - "post" : { - "description" : "", - "operationId" : "placeOrder", - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "order placed for purchasing the pet", - "required" : true - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid Order" - } - }, - "summary" : "Place an order for a pet", - "tags" : [ "store" ] - } - }, - "/store/order/{orderId}" : { - "delete" : { - "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "operationId" : "deleteOrder", - "parameters" : [ { - "description" : "ID of the order that needs to be deleted", - "explode" : false, - "in" : "path", - "name" : "orderId", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "responses" : { - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Order not found" - } - }, - "summary" : "Delete purchase order by ID", - "tags" : [ "store" ] - }, - "get" : { - "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions", - "operationId" : "getOrderById", - "parameters" : [ { - "description" : "ID of pet that needs to be fetched", - "explode" : false, - "in" : "path", - "name" : "orderId", - "required" : true, - "schema" : { - "format" : "int64", - "maximum" : 5, - "minimum" : 1, - "type" : "integer" - }, - "style" : "simple" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Order not found" - } - }, - "summary" : "Find purchase order by ID", - "tags" : [ "store" ] - } - }, - "/user" : { - "post" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "createUser", - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "Created user object", - "required" : true - }, - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Create user", - "tags" : [ "user" ] - } - }, - "/user/createWithArray" : { - "post" : { - "description" : "", - "operationId" : "createUsersWithArrayInput", - "requestBody" : { - "$ref" : "#/components/requestBodies/UserArray" - }, - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Creates list of users with given input array", - "tags" : [ "user" ] - } - }, - "/user/createWithList" : { - "post" : { - "description" : "", - "operationId" : "createUsersWithListInput", - "requestBody" : { - "$ref" : "#/components/requestBodies/UserArray" - }, - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Creates list of users with given input array", - "tags" : [ "user" ] - } - }, - "/user/login" : { - "get" : { - "description" : "", - "operationId" : "loginUser", - "parameters" : [ { - "description" : "The user name for login", - "explode" : true, - "in" : "query", - "name" : "username", - "required" : true, - "schema" : { - "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", - "type" : "string" - }, - "style" : "form" - }, { - "description" : "The password for login in clear text", - "explode" : true, - "in" : "query", - "name" : "password", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "type" : "string" - } - }, - "application/json" : { - "schema" : { - "type" : "string" - } - } - }, - "description" : "successful operation", - "headers" : { - "Set-Cookie" : { - "description" : "Cookie authentication key for use with the `api_key` apiKey authentication.", - "explode" : false, - "schema" : { - "example" : "AUTH_KEY=abcde12345; Path=/; HttpOnly", - "type" : "string" - }, - "style" : "simple" - }, - "X-Rate-Limit" : { - "description" : "calls per hour allowed by the user", - "explode" : false, - "schema" : { - "format" : "int32", - "type" : "integer" - }, - "style" : "simple" - }, - "X-Expires-After" : { - "description" : "date in UTC when token expires", - "explode" : false, - "schema" : { - "format" : "date-time", - "type" : "string" - }, - "style" : "simple" - } - } - }, - "400" : { - "description" : "Invalid username/password supplied" - } - }, - "summary" : "Logs user into the system", - "tags" : [ "user" ] - } - }, - "/user/logout" : { - "get" : { - "description" : "", - "operationId" : "logoutUser", - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Logs out current logged in user session", - "tags" : [ "user" ] - } - }, - "/user/{username}" : { - "delete" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "deleteUser", - "parameters" : [ { - "description" : "The name that needs to be deleted", - "explode" : false, - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "responses" : { - "400" : { - "description" : "Invalid username supplied" - }, - "404" : { - "description" : "User not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Delete user", - "tags" : [ "user" ] - }, - "get" : { - "description" : "", - "operationId" : "getUserByName", - "parameters" : [ { - "description" : "The name that needs to be fetched. Use user1 for testing.", - "explode" : false, - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "description" : "Invalid username supplied" - }, - "404" : { - "description" : "User not found" - } - }, - "summary" : "Get user by user name", - "tags" : [ "user" ] - }, - "put" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "updateUser", - "parameters" : [ { - "description" : "name that need to be deleted", - "explode" : false, - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - }, - "style" : "simple" - } ], - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "Updated user object", - "required" : true - }, - "responses" : { - "400" : { - "description" : "Invalid user supplied" - }, - "404" : { - "description" : "User not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Updated user", - "tags" : [ "user" ] - } - }, - "/fake/parameter_example_test" : { - "get" : { - "description" : "", - "operationId" : "fake_parameter_example_test", - "parameters" : [ { - "explode" : true, - "in" : "query", - "name" : "data", - "required" : true, - "schema" : { - "$ref" : "#/components/schemas/Pet" - }, - "style" : "form" - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - }, - "summary" : "fake endpoint to test parameter example (object)", - "tags" : [ "fake" ] - } - }, - "/fake/nullable_example_test" : { - "get" : { - "description" : "", - "operationId" : "fake_nullable_example_test", - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/TestNullable" - } - } - }, - "description" : "Successful operation" - } - }, - "summary" : "Fake endpoint to test nullable example (object)", - "tags" : [ "fake" ] - } - } - }, - "components" : { - "requestBodies" : { - "UserArray" : { - "content" : { - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/User" - }, - "type" : "array" - } - } - }, - "description" : "List of user object", - "required" : true - }, - "Pet" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "Pet object that needs to be added to the store", - "required" : true - } - }, - "schemas" : { - "TestEnum" : { - "enum" : [ "A", "B" ], - "type" : "string" - }, - "TestNullable" : { - "example" : { - "nullableName" : "nullableName", - "name" : "name" - }, - "properties" : { - "name" : { - "type" : "string" - }, - "nullableName" : { - "nullable" : true, - "type" : "string" - } - }, - "type" : "object" - }, - "Order" : { - "description" : "An order for a pets from the pet store", - "example" : { - "petId" : 6, - "quantity" : 1, - "id" : 0, - "shipDate" : "2000-01-23T04:56:07.000+00:00", - "complete" : false, - "status" : "placed" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "petId" : { - "format" : "int64", - "type" : "integer" - }, - "quantity" : { - "format" : "int32", - "type" : "integer" - }, - "shipDate" : { - "format" : "date-time", - "type" : "string" - }, - "status" : { - "description" : "Order Status", - "enum" : [ "placed", "approved", "delivered" ], - "type" : "string" - }, - "complete" : { - "default" : false, - "type" : "boolean" - } - }, - "title" : "Pet Order", - "type" : "object", - "xml" : { - "name" : "Order" - } - }, - "Category" : { - "description" : "A category for a pet", - "example" : { - "name" : "name", - "id" : 6 - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "name" : { - "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", - "type" : "string" - } - }, - "title" : "Pet category", - "type" : "object", - "xml" : { - "name" : "Category" - } - }, - "User" : { - "description" : "A User who is purchasing from the pet store", - "example" : { - "firstName" : "firstName", - "lastName" : "lastName", - "password" : "password", - "userStatus" : 6, - "phone" : "phone", - "id" : 0, - "email" : "email", - "username" : "username" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "username" : { - "type" : "string" - }, - "firstName" : { - "type" : "string" - }, - "lastName" : { - "type" : "string" - }, - "email" : { - "type" : "string" - }, - "password" : { - "type" : "string" - }, - "phone" : { - "type" : "string" - }, - "userStatus" : { - "description" : "User Status", - "format" : "int32", - "type" : "integer" - } - }, - "title" : "a User", - "type" : "object", - "xml" : { - "name" : "User" - } - }, - "Tag" : { - "description" : "A tag for a pet", - "example" : { - "name" : "name", - "id" : 1 - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "name" : { - "type" : "string" - } - }, - "title" : "Pet Tag", - "type" : "object", - "xml" : { - "name" : "Tag" - } - }, - "Pet" : { - "description" : "A pet for sale in the pet store", - "example" : { - "photoUrls" : [ "photoUrls", "photoUrls" ], - "name" : "doggie", - "id" : 0, - "category" : { - "name" : "name", - "id" : 6 - }, - "tags" : [ { - "name" : "name", - "id" : 1 - }, { - "name" : "name", - "id" : 1 - } ], - "status" : "available" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "category" : { - "$ref" : "#/components/schemas/Category" - }, - "name" : { - "example" : "doggie", - "type" : "string" - }, - "photoUrls" : { - "items" : { - "type" : "string" - }, - "type" : "array", - "xml" : { - "name" : "photoUrl", - "wrapped" : true - } - }, - "tags" : { - "items" : { - "$ref" : "#/components/schemas/Tag" - }, - "type" : "array", - "xml" : { - "name" : "tag", - "wrapped" : true - } - }, - "status" : { - "deprecated" : true, - "description" : "pet status in the store", - "enum" : [ "available", "pending", "sold" ], - "type" : "string" - } - }, - "required" : [ "name", "photoUrls" ], - "title" : "a Pet", - "type" : "object", - "xml" : { - "name" : "Pet" - } - }, - "ApiResponse" : { - "description" : "Describes the result of uploading an image resource", - "example" : { - "code" : 0, - "type" : "type", - "message" : "message" - }, - "properties" : { - "code" : { - "format" : "int32", - "type" : "integer" - }, - "type" : { - "type" : "string" - }, - "message" : { - "type" : "string" - } - }, - "title" : "An uploaded response", - "type" : "object" - }, - "Dog" : { - "allOf" : [ { - "$ref" : "#/components/schemas/Animal" - }, { - "properties" : { - "breed" : { - "type" : "string" - } - }, - "type" : "object" - } ] - }, - "Cat" : { - "allOf" : [ { - "$ref" : "#/components/schemas/Animal" - }, { - "properties" : { - "declawed" : { - "type" : "boolean" - } - }, - "type" : "object" - } ] - }, - "Animal" : { - "discriminator" : { - "mapping" : { - "DOG" : "#/components/schemas/Dog", - "CAT" : "#/components/schemas/Cat" - }, - "propertyName" : "className" - }, - "properties" : { - "className" : { - "type" : "string" - }, - "color" : { - "default" : "red", - "type" : "string" - } - }, - "required" : [ "className" ], - "type" : "object" - }, - "updatePetWithForm_request" : { - "properties" : { - "name" : { - "description" : "Updated name of the pet", - "type" : "string" - }, - "status" : { - "description" : "Updated status of the pet", - "type" : "string" - } - }, - "type" : "object" - }, - "uploadFile_request" : { - "properties" : { - "additionalMetadata" : { - "description" : "Additional data to pass to server", - "type" : "string" - }, - "file" : { - "description" : "file to upload", - "format" : "binary", - "type" : "string" - } - }, - "type" : "object" - } - }, - "securitySchemes" : { - "petstore_auth" : { - "flows" : { - "implicit" : { - "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", - "scopes" : { - "write:pets" : "modify pets in your account", - "read:pets" : "read your pets" - } - } - }, - "type" : "oauth2" - }, - "api_key" : { - "in" : "header", - "name" : "api_key", - "type" : "apiKey" - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Dockerfile b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Dockerfile index e69de29bb2d1..c24f45dbc5a4 100644 --- a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Dockerfile +++ b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Dockerfile @@ -0,0 +1,32 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +# Container we use for final publish +FROM mcr.microsoft.com/dotnet/core/aspnet:8.0-buster-slim AS base +WORKDIR /app +EXPOSE 80 +EXPOSE 443 + +# Build container +FROM mcr.microsoft.com/dotnet/core/sdk:8.0-buster AS build + +# Copy the code into the container +WORKDIR /src +COPY ["src/Org.OpenAPITools/Org.OpenAPITools.csproj", "Org.OpenAPITools/"] + +# NuGet restore +RUN dotnet restore "Org.OpenAPITools/Org.OpenAPITools.csproj" +COPY ["src/Org.OpenAPITools/", "Org.OpenAPITools/"] + +# Build the API +WORKDIR "Org.OpenAPITools" +RUN dotnet build "Org.OpenAPITools.csproj" -c Release -o /app/build + +# Publish it +FROM build AS publish +RUN dotnet publish "Org.OpenAPITools.csproj" -c Release -o /app/publish + +# Make the final image for publishing +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Org.OpenAPITools.dll"] diff --git a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/.openapi-generator/VERSION index 193a12d6e891..909dcd0eca63 100644 --- a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/.openapi-generator/VERSION @@ -1 +1 @@ -7.20.0-SNAPSHOT +7.19.0-SNAPSHOT diff --git a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs index e69de29bb2d1..18796da30fcb 100644 --- a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs +++ b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Formatters/InputFormatterStream.cs @@ -0,0 +1,45 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System; +using System.IO; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.Formatters; + +namespace Org.OpenAPITools.Formatters +{ + /// + public class InputFormatterStream : InputFormatter + { + /// + public InputFormatterStream() + { + SupportedMediaTypes.Add("application/octet-stream"); + SupportedMediaTypes.Add("image/jpeg"); + } + + /// + public override Task ReadRequestBodyAsync(InputFormatterContext context) + { + return InputFormatterResult.SuccessAsync(context.HttpContext.Request.Body); + } + + /// + protected override bool CanReadType(Type type) + { + if (type == typeof(Stream)) + { + return true; + } + + return false; + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec index e69de29bb2d1..b1d83a359618 100644 --- a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec +++ b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/src/Org.OpenAPITools/Org.OpenAPITools.nuspec @@ -0,0 +1,20 @@ + + + + $id$ + 1.0.0 + OpenAPI Library + OpenAPI + OpenAPI + https://www.apache.org/licenses/LICENSE-2.0.html + + false + A library generated from a OpenAPI doc + Summary of changes made in this release of the package. + No Copyright + Org.OpenAPITools + + diff --git a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index 9eccd5c317f6..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -1,107 +0,0 @@ -/* - * OpenAPI Petstore - * - * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - * - * The version of the OpenAPI document: 1.0.0 - * - * Generated by: https://openapi-generator.tech - */ - -using System.ComponentModel.DataAnnotations; -using System.Linq; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.OpenApi.Models; -using Swashbuckle.AspNetCore.SwaggerGen; - -namespace Org.OpenAPITools.Filters -{ - /// - /// Path Parameter Validation Rules Filter - /// - public class GeneratePathParamsValidationFilter : IOperationFilter - { - /// - /// Constructor - /// - /// Operation - /// OperationFilterContext - public void Apply(OpenApiOperation operation, OperationFilterContext context) - { - var pars = context.ApiDescription.ParameterDescriptions; - - foreach (var par in pars) - { - var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); - - var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); - - // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 - // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 - // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema - if (attributes.Any() && openapiParam != null) - { - // Required - [Required] - var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); - if (requiredAttr != null) - { - openapiParam.Required = true; - } - - // Regex Pattern [RegularExpression] - var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); - if (regexAttr != null) - { - var regex = (string)regexAttr.ConstructorArguments[0].Value; - openapiParam.Schema.Pattern = regex; - } - - // String Length [StringLength] - int? minLength = null, maxLength = null; - var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); - if (stringLengthAttr != null) - { - if (stringLengthAttr.NamedArguments.Count == 1) - { - minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; - } - maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; - } - - var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); - if (minLengthAttr != null) - { - minLength = (int)minLengthAttr.ConstructorArguments[0].Value; - } - - var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); - if (maxLengthAttr != null) - { - maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; - } - - if (minLength != null) - { - openapiParam.Schema.MinLength = minLength; - } - - if (maxLength != null) - { - openapiParam.Schema.MaxLength = maxLength; - } - - // Range [Range] - var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); - if (rangeAttr != null) - { - var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; - var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; - - openapiParam.Schema.MinLength = rangeMin; - openapiParam.Schema.MaxLength = rangeMax; - } - } - } - } - } -} diff --git a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Program.cs b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Program.cs index e69de29bb2d1..00ed16ed6758 100644 --- a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Program.cs +++ b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Program.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; + +namespace Org.OpenAPITools +{ + /// + /// Program + /// + public class Program + { + /// + /// Main + /// + /// + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + /// + /// Create the host builder. + /// + /// + /// IHostBuilder + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup() + .UseUrls("http://0.0.0.0:8080/"); + }); + } +} diff --git a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/appsettings.json b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/appsettings.json index e69de29bb2d1..def9159a7d94 100644 --- a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/appsettings.json +++ b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/appsettings.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Properties/launchSettings.json b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Properties/launchSettings.json index e69de29bb2d1..1b527df2c2b3 100644 --- a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Properties/launchSettings.json +++ b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/Properties/launchSettings.json @@ -0,0 +1,30 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:61788", + "sslPort": 44301 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "api/values", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "WebApplication1": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "api/values", + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/wwwroot/openapi-original.json index 333dcf2bfceb..e69de29bb2d1 100644 --- a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/wwwroot/openapi-original.json +++ b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/wwwroot/openapi-original.json @@ -1,1021 +0,0 @@ -{ - "openapi" : "3.0.1", - "info" : { - "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", - "license" : { - "name" : "Apache-2.0", - "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" - }, - "title" : "OpenAPI Petstore", - "version" : "1.0.0" - }, - "servers" : [ { - "url" : "http://petstore.swagger.io/v2" - } ], - "tags" : [ { - "description" : "Everything about your Pets", - "name" : "pet" - }, { - "description" : "Access to Petstore orders", - "name" : "store" - }, { - "description" : "Operations about user", - "name" : "user" - } ], - "paths" : { - "/pet" : { - "post" : { - "operationId" : "addPet", - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "Pet object that needs to be added to the store", - "required" : true - }, - "responses" : { - "405" : { - "content" : { }, - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Add a new pet to the store", - "tags" : [ "pet" ], - "x-codegen-request-body-name" : "body" - }, - "put" : { - "operationId" : "updatePet", - "requestBody" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "Pet object that needs to be added to the store", - "required" : true - }, - "responses" : { - "400" : { - "content" : { }, - "description" : "Invalid ID supplied" - }, - "404" : { - "content" : { }, - "description" : "Pet not found" - }, - "405" : { - "content" : { }, - "description" : "Validation exception" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Update an existing pet", - "tags" : [ "pet" ], - "x-codegen-request-body-name" : "body" - } - }, - "/pet/findByStatus" : { - "get" : { - "description" : "Multiple status values can be provided with comma separated strings", - "operationId" : "findPetsByStatus", - "parameters" : [ { - "description" : "Status values that need to be considered for filter", - "explode" : false, - "in" : "query", - "name" : "status", - "required" : true, - "schema" : { - "items" : { - "default" : "available", - "enum" : [ "available", "pending", "sold" ], - "type" : "string" - }, - "type" : "array" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - }, - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "content" : { }, - "description" : "Invalid status value" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Finds Pets by status", - "tags" : [ "pet" ] - } - }, - "/pet/findByTags" : { - "get" : { - "deprecated" : true, - "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", - "operationId" : "findPetsByTags", - "parameters" : [ { - "description" : "Tags to filter by", - "explode" : false, - "in" : "query", - "name" : "tags", - "required" : true, - "schema" : { - "items" : { - "type" : "string" - }, - "type" : "array" - }, - "style" : "form" - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - }, - "application/json" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/Pet" - }, - "type" : "array" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "content" : { }, - "description" : "Invalid tag value" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Finds Pets by tags", - "tags" : [ "pet" ] - } - }, - "/pet/{petId}" : { - "delete" : { - "operationId" : "deletePet", - "parameters" : [ { - "in" : "header", - "name" : "api_key", - "schema" : { - "type" : "string" - } - }, { - "description" : "Pet id to delete", - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - } - } ], - "responses" : { - "400" : { - "content" : { }, - "description" : "Invalid pet value" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Deletes a pet", - "tags" : [ "pet" ] - }, - "get" : { - "description" : "Returns a single pet", - "operationId" : "getPetById", - "parameters" : [ { - "description" : "ID of pet to return", - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - } - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Pet" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "content" : { }, - "description" : "Invalid ID supplied" - }, - "404" : { - "content" : { }, - "description" : "Pet not found" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Find pet by ID", - "tags" : [ "pet" ] - }, - "post" : { - "operationId" : "updatePetWithForm", - "parameters" : [ { - "description" : "ID of pet that needs to be updated", - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - } - } ], - "requestBody" : { - "content" : { - "application/x-www-form-urlencoded" : { - "schema" : { - "$ref" : "#/components/schemas/updatePetWithForm_request" - } - } - } - }, - "responses" : { - "405" : { - "content" : { }, - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "Updates a pet in the store with form data", - "tags" : [ "pet" ] - } - }, - "/pet/{petId}/uploadImage" : { - "post" : { - "operationId" : "uploadFile", - "parameters" : [ { - "description" : "ID of pet to update", - "in" : "path", - "name" : "petId", - "required" : true, - "schema" : { - "format" : "int64", - "type" : "integer" - } - } ], - "requestBody" : { - "content" : { - "multipart/form-data" : { - "schema" : { - "$ref" : "#/components/schemas/uploadFile_request" - } - } - } - }, - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ApiResponse" - } - } - }, - "description" : "successful operation" - } - }, - "security" : [ { - "petstore_auth" : [ "write:pets", "read:pets" ] - } ], - "summary" : "uploads an image", - "tags" : [ "pet" ] - } - }, - "/store/inventory" : { - "get" : { - "description" : "Returns a map of status codes to quantities", - "operationId" : "getInventory", - "responses" : { - "200" : { - "content" : { - "application/json" : { - "schema" : { - "additionalProperties" : { - "format" : "int32", - "type" : "integer" - }, - "type" : "object" - } - } - }, - "description" : "successful operation" - } - }, - "security" : [ { - "api_key" : [ ] - } ], - "summary" : "Returns pet inventories by status", - "tags" : [ "store" ] - } - }, - "/store/order" : { - "post" : { - "operationId" : "placeOrder", - "requestBody" : { - "content" : { - "*/*" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "order placed for purchasing the pet", - "required" : true - }, - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "content" : { }, - "description" : "Invalid Order" - } - }, - "summary" : "Place an order for a pet", - "tags" : [ "store" ], - "x-codegen-request-body-name" : "body" - } - }, - "/store/order/{orderId}" : { - "delete" : { - "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "operationId" : "deleteOrder", - "parameters" : [ { - "description" : "ID of the order that needs to be deleted", - "in" : "path", - "name" : "orderId", - "required" : true, - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "400" : { - "content" : { }, - "description" : "Invalid ID supplied" - }, - "404" : { - "content" : { }, - "description" : "Order not found" - } - }, - "summary" : "Delete purchase order by ID", - "tags" : [ "store" ] - }, - "get" : { - "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions", - "operationId" : "getOrderById", - "parameters" : [ { - "description" : "ID of pet that needs to be fetched", - "in" : "path", - "name" : "orderId", - "required" : true, - "schema" : { - "format" : "int64", - "maximum" : 5, - "minimum" : 1, - "type" : "integer" - } - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Order" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "content" : { }, - "description" : "Invalid ID supplied" - }, - "404" : { - "content" : { }, - "description" : "Order not found" - } - }, - "summary" : "Find purchase order by ID", - "tags" : [ "store" ] - } - }, - "/user" : { - "post" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "createUser", - "requestBody" : { - "content" : { - "*/*" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "Created user object", - "required" : true - }, - "responses" : { - "default" : { - "content" : { }, - "description" : "successful operation" - } - }, - "summary" : "Create user", - "tags" : [ "user" ], - "x-codegen-request-body-name" : "body" - } - }, - "/user/createWithArray" : { - "post" : { - "operationId" : "createUsersWithArrayInput", - "requestBody" : { - "content" : { - "*/*" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/User" - }, - "type" : "array" - } - } - }, - "description" : "List of user object", - "required" : true - }, - "responses" : { - "default" : { - "content" : { }, - "description" : "successful operation" - } - }, - "summary" : "Creates list of users with given input array", - "tags" : [ "user" ], - "x-codegen-request-body-name" : "body" - } - }, - "/user/createWithList" : { - "post" : { - "operationId" : "createUsersWithListInput", - "requestBody" : { - "content" : { - "*/*" : { - "schema" : { - "items" : { - "$ref" : "#/components/schemas/User" - }, - "type" : "array" - } - } - }, - "description" : "List of user object", - "required" : true - }, - "responses" : { - "default" : { - "content" : { }, - "description" : "successful operation" - } - }, - "summary" : "Creates list of users with given input array", - "tags" : [ "user" ], - "x-codegen-request-body-name" : "body" - } - }, - "/user/login" : { - "get" : { - "operationId" : "loginUser", - "parameters" : [ { - "description" : "The user name for login", - "in" : "query", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - } - }, { - "description" : "The password for login in clear text", - "in" : "query", - "name" : "password", - "required" : true, - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "type" : "string" - } - }, - "application/json" : { - "schema" : { - "type" : "string" - } - } - }, - "description" : "successful operation", - "headers" : { - "X-Rate-Limit" : { - "description" : "calls per hour allowed by the user", - "schema" : { - "format" : "int32", - "type" : "integer" - } - }, - "X-Expires-After" : { - "description" : "date in UTC when token expires", - "schema" : { - "format" : "date-time", - "type" : "string" - } - } - } - }, - "400" : { - "content" : { }, - "description" : "Invalid username/password supplied" - } - }, - "summary" : "Logs user into the system", - "tags" : [ "user" ] - } - }, - "/user/logout" : { - "get" : { - "operationId" : "logoutUser", - "responses" : { - "default" : { - "content" : { }, - "description" : "successful operation" - } - }, - "summary" : "Logs out current logged in user session", - "tags" : [ "user" ] - } - }, - "/user/{username}" : { - "delete" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "deleteUser", - "parameters" : [ { - "description" : "The name that needs to be deleted", - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "400" : { - "content" : { }, - "description" : "Invalid username supplied" - }, - "404" : { - "content" : { }, - "description" : "User not found" - } - }, - "summary" : "Delete user", - "tags" : [ "user" ] - }, - "get" : { - "operationId" : "getUserByName", - "parameters" : [ { - "description" : "The name that needs to be fetched. Use user1 for testing.", - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - } - } ], - "responses" : { - "200" : { - "content" : { - "application/xml" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - }, - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "successful operation" - }, - "400" : { - "content" : { }, - "description" : "Invalid username supplied" - }, - "404" : { - "content" : { }, - "description" : "User not found" - } - }, - "summary" : "Get user by user name", - "tags" : [ "user" ] - }, - "put" : { - "description" : "This can only be done by the logged in user.", - "operationId" : "updateUser", - "parameters" : [ { - "description" : "name that need to be deleted", - "in" : "path", - "name" : "username", - "required" : true, - "schema" : { - "type" : "string" - } - } ], - "requestBody" : { - "content" : { - "*/*" : { - "schema" : { - "$ref" : "#/components/schemas/User" - } - } - }, - "description" : "Updated user object", - "required" : true - }, - "responses" : { - "400" : { - "content" : { }, - "description" : "Invalid user supplied" - }, - "404" : { - "content" : { }, - "description" : "User not found" - } - }, - "summary" : "Updated user", - "tags" : [ "user" ], - "x-codegen-request-body-name" : "body" - } - } - }, - "components" : { - "schemas" : { - "Order" : { - "description" : "An order for a pets from the pet store", - "example" : { - "petId" : 6, - "quantity" : 1, - "id" : 0, - "shipDate" : "2000-01-23T04:56:07.000+00:00", - "complete" : false, - "status" : "placed" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "petId" : { - "format" : "int64", - "type" : "integer" - }, - "quantity" : { - "format" : "int32", - "type" : "integer" - }, - "shipDate" : { - "format" : "date-time", - "type" : "string" - }, - "status" : { - "description" : "Order Status", - "enum" : [ "placed", "approved", "delivered" ], - "type" : "string" - }, - "complete" : { - "default" : false, - "type" : "boolean" - } - }, - "title" : "Pet Order", - "type" : "object", - "xml" : { - "name" : "Order" - } - }, - "Category" : { - "description" : "A category for a pet", - "example" : { - "name" : "name", - "id" : 6 - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "name" : { - "type" : "string" - } - }, - "title" : "Pet category", - "type" : "object", - "xml" : { - "name" : "Category" - } - }, - "User" : { - "description" : "A User who is purchasing from the pet store", - "example" : { - "firstName" : "firstName", - "lastName" : "lastName", - "password" : "password", - "userStatus" : 6, - "phone" : "phone", - "id" : 0, - "email" : "email", - "username" : "username" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "username" : { - "type" : "string" - }, - "firstName" : { - "type" : "string" - }, - "lastName" : { - "type" : "string" - }, - "email" : { - "type" : "string" - }, - "password" : { - "type" : "string" - }, - "phone" : { - "type" : "string" - }, - "userStatus" : { - "description" : "User Status", - "format" : "int32", - "type" : "integer" - } - }, - "title" : "a User", - "type" : "object", - "xml" : { - "name" : "User" - } - }, - "Tag" : { - "description" : "A tag for a pet", - "example" : { - "name" : "name", - "id" : 1 - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "name" : { - "type" : "string" - } - }, - "title" : "Pet Tag", - "type" : "object", - "xml" : { - "name" : "Tag" - } - }, - "Pet" : { - "description" : "A pet for sale in the pet store", - "example" : { - "photoUrls" : [ "photoUrls", "photoUrls" ], - "name" : "doggie", - "id" : 0, - "category" : { - "name" : "name", - "id" : 6 - }, - "tags" : [ { - "name" : "name", - "id" : 1 - }, { - "name" : "name", - "id" : 1 - } ], - "status" : "available" - }, - "properties" : { - "id" : { - "format" : "int64", - "type" : "integer" - }, - "category" : { - "$ref" : "#/components/schemas/Category" - }, - "name" : { - "example" : "doggie", - "type" : "string" - }, - "photoUrls" : { - "items" : { - "type" : "string" - }, - "type" : "array", - "xml" : { - "name" : "photoUrl", - "wrapped" : true - } - }, - "tags" : { - "items" : { - "$ref" : "#/components/schemas/Tag" - }, - "type" : "array", - "xml" : { - "name" : "tag", - "wrapped" : true - } - }, - "status" : { - "description" : "pet status in the store", - "enum" : [ "available", "pending", "sold" ], - "type" : "string" - } - }, - "required" : [ "name", "photoUrls" ], - "title" : "a Pet", - "type" : "object", - "xml" : { - "name" : "Pet" - } - }, - "ApiResponse" : { - "description" : "Describes the result of uploading an image resource", - "example" : { - "code" : 0, - "type" : "type", - "message" : "message" - }, - "properties" : { - "code" : { - "format" : "int32", - "type" : "integer" - }, - "type" : { - "type" : "string" - }, - "message" : { - "type" : "string" - } - }, - "title" : "An uploaded response", - "type" : "object" - }, - "updatePetWithForm_request" : { - "properties" : { - "name" : { - "description" : "Updated name of the pet", - "type" : "string" - }, - "status" : { - "description" : "Updated status of the pet", - "type" : "string" - } - }, - "type" : "object" - }, - "uploadFile_request" : { - "properties" : { - "additionalMetadata" : { - "description" : "Additional data to pass to server", - "type" : "string" - }, - "file" : { - "description" : "file to upload", - "format" : "binary", - "type" : "string" - } - }, - "type" : "object" - } - }, - "securitySchemes" : { - "petstore_auth" : { - "flows" : { - "implicit" : { - "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", - "scopes" : { - "write:pets" : "modify pets in your account", - "read:pets" : "read your pets" - } - } - }, - "type" : "oauth2" - }, - "api_key" : { - "in" : "header", - "name" : "api_key", - "type" : "apiKey" - } - } - }, - "x-original-swagger-version" : "2.0" -} diff --git a/samples/server/petstore/cpp-oatpp/model/Order.hpp b/samples/server/petstore/cpp-oatpp/model/Order.hpp index 3f69abb6a203..e69de29bb2d1 100644 --- a/samples/server/petstore/cpp-oatpp/model/Order.hpp +++ b/samples/server/petstore/cpp-oatpp/model/Order.hpp @@ -1,59 +0,0 @@ -/** -* OpenAPI Petstore -* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ -/* - * Order.h - * - * An order for a pets from the pet store - */ - -#ifndef Order_H_ -#define Order_H_ - - -#include "oatpp/core/macro/codegen.hpp" -#include "oatpp/core/Types.hpp" - -namespace org::openapitools::server::model -{ - -/* Begin DTO code-generation */ -#include OATPP_CODEGEN_BEGIN(DTO) - -/** - * Message Data-Transfer-Object - */ -class Order : public oatpp::DTO { - - DTO_INIT(Order, DTO /* Extends */) - - DTO_FIELD(oatpp::Int64, id); - DTO_FIELD(oatpp::Boolean, idIsSet); - DTO_FIELD(oatpp::Int64, petId); - DTO_FIELD(oatpp::Boolean, petIdIsSet); - DTO_FIELD(oatpp::Int32, quantity); - DTO_FIELD(oatpp::Boolean, quantityIsSet); - DTO_FIELD(oatpp::String, shipDate); - DTO_FIELD(oatpp::Boolean, shipDateIsSet); - DTO_FIELD(oatpp::String, status); - DTO_FIELD(oatpp::Boolean, statusIsSet); - DTO_FIELD(oatpp::Boolean, complete); - DTO_FIELD(oatpp::Boolean, completeIsSet); - -}; - -/* End DTO code-generation */ -#include OATPP_CODEGEN_END(DTO) - - -} // namespace org::openapitools::server::model - -#endif /* Order_H_ */ diff --git a/samples/server/petstore/cpp-pistache-everything/model/Order.cpp b/samples/server/petstore/cpp-pistache-everything/model/Order.cpp index 459d6ee5d69a..e69de29bb2d1 100644 --- a/samples/server/petstore/cpp-pistache-everything/model/Order.cpp +++ b/samples/server/petstore/cpp-pistache-everything/model/Order.cpp @@ -1,251 +0,0 @@ -/** -* OpenAPI Petstore -* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ - - -#include "Order.h" -#include "Helpers.h" - -#include - -namespace org::openapitools::server::model -{ - -Order::Order() -{ - m_Id = 0L; - m_IdIsSet = false; - m_PetId = 0L; - m_PetIdIsSet = false; - m_Quantity = 0; - m_QuantityIsSet = false; - m_ShipDate = ""; - m_ShipDateIsSet = false; - m_Status = ""; - m_StatusIsSet = false; - m_Complete = false; - m_CompleteIsSet = false; - -} - -void Order::validate() const -{ - std::stringstream msg; - if (!validate(msg)) - { - throw org::openapitools::server::helpers::ValidationException(msg.str()); - } -} - -bool Order::validate(std::stringstream& msg) const -{ - return validate(msg, ""); -} - -bool Order::validate(std::stringstream& msg, const std::string& pathPrefix) const -{ - bool success = true; - const std::string _pathPrefix = pathPrefix.empty() ? "Order" : pathPrefix; - - - return success; -} - -bool Order::operator==(const Order& rhs) const -{ - return - - - - ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && - - - ((!petIdIsSet() && !rhs.petIdIsSet()) || (petIdIsSet() && rhs.petIdIsSet() && getPetId() == rhs.getPetId())) && - - - ((!quantityIsSet() && !rhs.quantityIsSet()) || (quantityIsSet() && rhs.quantityIsSet() && getQuantity() == rhs.getQuantity())) && - - - ((!shipDateIsSet() && !rhs.shipDateIsSet()) || (shipDateIsSet() && rhs.shipDateIsSet() && getShipDate() == rhs.getShipDate())) && - - - ((!statusIsSet() && !rhs.statusIsSet()) || (statusIsSet() && rhs.statusIsSet() && getStatus() == rhs.getStatus())) && - - - ((!completeIsSet() && !rhs.completeIsSet()) || (completeIsSet() && rhs.completeIsSet() && isComplete() == rhs.isComplete())) - - ; -} - -bool Order::operator!=(const Order& rhs) const -{ - return !(*this == rhs); -} - -void to_json(nlohmann::json& j, const Order& o) -{ - j = nlohmann::json::object(); - if(o.idIsSet()) - j["id"] = o.m_Id; - if(o.petIdIsSet()) - j["petId"] = o.m_PetId; - if(o.quantityIsSet()) - j["quantity"] = o.m_Quantity; - if(o.shipDateIsSet()) - j["shipDate"] = o.m_ShipDate; - if(o.statusIsSet()) - j["status"] = o.m_Status; - if(o.completeIsSet()) - j["complete"] = o.m_Complete; - -} - -void from_json(const nlohmann::json& j, Order& o) -{ - if(j.find("id") != j.end()) - { - j.at("id").get_to(o.m_Id); - o.m_IdIsSet = true; - } - if(j.find("petId") != j.end()) - { - j.at("petId").get_to(o.m_PetId); - o.m_PetIdIsSet = true; - } - if(j.find("quantity") != j.end()) - { - j.at("quantity").get_to(o.m_Quantity); - o.m_QuantityIsSet = true; - } - if(j.find("shipDate") != j.end()) - { - j.at("shipDate").get_to(o.m_ShipDate); - o.m_ShipDateIsSet = true; - } - if(j.find("status") != j.end()) - { - j.at("status").get_to(o.m_Status); - o.m_StatusIsSet = true; - } - if(j.find("complete") != j.end()) - { - j.at("complete").get_to(o.m_Complete); - o.m_CompleteIsSet = true; - } - -} - -int64_t Order::getId() const -{ - return m_Id; -} -void Order::setId(int64_t const value) -{ - m_Id = value; - m_IdIsSet = true; -} -bool Order::idIsSet() const -{ - return m_IdIsSet; -} -void Order::unsetId() -{ - m_IdIsSet = false; -} -int64_t Order::getPetId() const -{ - return m_PetId; -} -void Order::setPetId(int64_t const value) -{ - m_PetId = value; - m_PetIdIsSet = true; -} -bool Order::petIdIsSet() const -{ - return m_PetIdIsSet; -} -void Order::unsetPetId() -{ - m_PetIdIsSet = false; -} -int32_t Order::getQuantity() const -{ - return m_Quantity; -} -void Order::setQuantity(int32_t const value) -{ - m_Quantity = value; - m_QuantityIsSet = true; -} -bool Order::quantityIsSet() const -{ - return m_QuantityIsSet; -} -void Order::unsetQuantity() -{ - m_QuantityIsSet = false; -} -std::string Order::getShipDate() const -{ - return m_ShipDate; -} -void Order::setShipDate(std::string const& value) -{ - m_ShipDate = value; - m_ShipDateIsSet = true; -} -bool Order::shipDateIsSet() const -{ - return m_ShipDateIsSet; -} -void Order::unsetShipDate() -{ - m_ShipDateIsSet = false; -} -std::string Order::getStatus() const -{ - return m_Status; -} -void Order::setStatus(std::string const& value) -{ - m_Status = value; - m_StatusIsSet = true; -} -bool Order::statusIsSet() const -{ - return m_StatusIsSet; -} -void Order::unsetStatus() -{ - m_StatusIsSet = false; -} -bool Order::isComplete() const -{ - return m_Complete; -} -void Order::setComplete(bool const value) -{ - m_Complete = value; - m_CompleteIsSet = true; -} -bool Order::completeIsSet() const -{ - return m_CompleteIsSet; -} -void Order::unsetComplete() -{ - m_CompleteIsSet = false; -} - - -} // namespace org::openapitools::server::model - diff --git a/samples/server/petstore/cpp-pistache-everything/model/Order.h b/samples/server/petstore/cpp-pistache-everything/model/Order.h index e69de29bb2d1..78a6c8805bbe 100644 --- a/samples/server/petstore/cpp-pistache-everything/model/Order.h +++ b/samples/server/petstore/cpp-pistache-everything/model/Order.h @@ -0,0 +1,124 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +/* + * Order.h + * + * An order for a pets from the pet store + */ + +#ifndef Order_H_ +#define Order_H_ + + +#include +#include + +namespace org::openapitools::server::model +{ + +/// +/// An order for a pets from the pet store +/// +class Order +{ +public: + Order(); + virtual ~Order() = default; + + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + /// + /// Helper overload for validate. Used when one model stores another model and calls it's validate. + /// Not meant to be called outside that case. + /// + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + + bool operator==(const Order& rhs) const; + bool operator!=(const Order& rhs) const; + + ///////////////////////////////////////////// + /// Order members + + /// + /// + /// + int64_t getId() const; + void setId(int64_t const value); + bool idIsSet() const; + void unsetId(); + /// + /// + /// + int64_t getPetId() const; + void setPetId(int64_t const value); + bool petIdIsSet() const; + void unsetPetId(); + /// + /// + /// + int32_t getQuantity() const; + void setQuantity(int32_t const value); + bool quantityIsSet() const; + void unsetQuantity(); + /// + /// + /// + std::string getShipDate() const; + void setShipDate(std::string const& value); + bool shipDateIsSet() const; + void unsetShipDate(); + /// + /// Order Status + /// + std::string getStatus() const; + void setStatus(std::string const& value); + bool statusIsSet() const; + void unsetStatus(); + /// + /// + /// + bool isComplete() const; + void setComplete(bool const value); + bool completeIsSet() const; + void unsetComplete(); + + friend void to_json(nlohmann::json& j, const Order& o); + friend void from_json(const nlohmann::json& j, Order& o); +protected: + int64_t m_Id; + bool m_IdIsSet; + int64_t m_PetId; + bool m_PetIdIsSet; + int32_t m_Quantity; + bool m_QuantityIsSet; + std::string m_ShipDate; + bool m_ShipDateIsSet; + std::string m_Status; + bool m_StatusIsSet; + bool m_Complete; + bool m_CompleteIsSet; + +}; + +} // namespace org::openapitools::server::model + +#endif /* Order_H_ */ diff --git a/samples/server/petstore/cpp-pistache-nested-schema-refs/api/StoreApi.cpp b/samples/server/petstore/cpp-pistache-nested-schema-refs/api/StoreApi.cpp index d23f51da8fd2..e69de29bb2d1 100644 --- a/samples/server/petstore/cpp-pistache-nested-schema-refs/api/StoreApi.cpp +++ b/samples/server/petstore/cpp-pistache-nested-schema-refs/api/StoreApi.cpp @@ -1,103 +0,0 @@ -/** -* Test swagger file -* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ - -#include "StoreApi.h" -#include "Helpers.h" - -namespace org::openapitools::server::api -{ - -using namespace org::openapitools::server::helpers; -using namespace org::openapitools::server::model; - -const std::string StoreApi::base = ""; - -StoreApi::StoreApi(const std::shared_ptr& rtr) - : ApiBase(rtr) -{} - -void StoreApi::init() { - setupRoutes(); -} - -void StoreApi::setupRoutes() { - using namespace Pistache::Rest; - - Routes::Get(*router, base + "/pet", Routes::bind(&StoreApi::get_nested_object_handler, this)); - - // Default handler, called when a route is not found - router->addCustomHandler(Routes::bind(&StoreApi::store_api_default_handler, this)); -} - -void StoreApi::handleParsingException(const std::exception& ex, Pistache::Http::ResponseWriter &response) const noexcept { - std::pair codeAndError = handleParsingException(ex); - response.send(codeAndError.first, codeAndError.second); -} - -std::pair StoreApi::handleParsingException(const std::exception& ex) const noexcept { - try { - throw; - } catch (nlohmann::detail::exception &e) { - return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); - } catch (org::openapitools::server::helpers::ValidationException &e) { - return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); - } catch (std::exception &e) { - return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what()); - } -} - -void StoreApi::handleOperationException(const std::exception& ex, Pistache::Http::ResponseWriter &response) const noexcept { - std::pair codeAndError = handleOperationException(ex); - response.send(codeAndError.first, codeAndError.second); -} - -std::pair StoreApi::handleOperationException(const std::exception& ex) const noexcept { - return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); -} - -void StoreApi::get_nested_object_handler(const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { - try { - - - - - - - try { - - - - - - this->get_nested_object(response); - } catch (Pistache::Http::HttpError &e) { - response.send(static_cast(e.code()), e.what()); - return; - } catch (std::exception &e) { - this->handleOperationException(e, response); - return; - } - - } catch (std::exception &e) { - response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); - } - - -} - - -void StoreApi::store_api_default_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { - response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); -} - -} // namespace org::openapitools::server::api - diff --git a/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.cpp b/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.cpp index e69de29bb2d1..f3cc1f8076b4 100644 --- a/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.cpp +++ b/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.cpp @@ -0,0 +1,94 @@ +/** +* Test swagger file +* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + + +#include "OuterType.h" +#include "Helpers.h" + +#include + +namespace org::openapitools::server::model +{ + +OuterType::OuterType() +{ + +} + +void OuterType::validate() const +{ + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } +} + +bool OuterType::validate(std::stringstream& msg) const +{ + return validate(msg, ""); +} + +bool OuterType::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "OuterType" : pathPrefix; + + + if (!m_Middle.validate(msg, _pathPrefix + ".middle")) { + msg << _pathPrefix << ": Middle is invalid;"; + success = false; + } + return success; +} + +bool OuterType::operator==(const OuterType& rhs) const +{ + return + + + (getMiddle() == rhs.getMiddle()) + + + ; +} + +bool OuterType::operator!=(const OuterType& rhs) const +{ + return !(*this == rhs); +} + +void to_json(nlohmann::json& j, const OuterType& o) +{ + j = nlohmann::json::object(); + j["middle"] = o.m_Middle; + +} + +void from_json(const nlohmann::json& j, OuterType& o) +{ + j.at("middle").get_to(o.m_Middle); + +} + +org::openapitools::server::model::MiddleType OuterType::getMiddle() const +{ + return m_Middle; +} +void OuterType::setMiddle(org::openapitools::server::model::MiddleType const& value) +{ + m_Middle = value; +} + + +} // namespace org::openapitools::server::model + diff --git a/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.h b/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.h index e69de29bb2d1..df53df3c2be7 100644 --- a/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.h +++ b/samples/server/petstore/cpp-pistache-nested-schema-refs/model/OuterType.h @@ -0,0 +1,77 @@ +/** +* Test swagger file +* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +/* + * OuterType.h + * + * + */ + +#ifndef OuterType_H_ +#define OuterType_H_ + + +#include "MiddleType.h" +#include + +namespace org::openapitools::server::model +{ + +/// +/// +/// +class OuterType +{ +public: + OuterType(); + virtual ~OuterType() = default; + + + /// + /// Validate the current data in the model. Throws a ValidationException on failure. + /// + void validate() const; + + /// + /// Validate the current data in the model. Returns false on error and writes an error + /// message into the given stringstream. + /// + bool validate(std::stringstream& msg) const; + + /// + /// Helper overload for validate. Used when one model stores another model and calls it's validate. + /// Not meant to be called outside that case. + /// + bool validate(std::stringstream& msg, const std::string& pathPrefix) const; + + bool operator==(const OuterType& rhs) const; + bool operator!=(const OuterType& rhs) const; + + ///////////////////////////////////////////// + /// OuterType members + + /// + /// + /// + org::openapitools::server::model::MiddleType getMiddle() const; + void setMiddle(org::openapitools::server::model::MiddleType const& value); + + friend void to_json(nlohmann::json& j, const OuterType& o); + friend void from_json(const nlohmann::json& j, OuterType& o); +protected: + org::openapitools::server::model::MiddleType m_Middle; + + +}; + +} // namespace org::openapitools::server::model + +#endif /* OuterType_H_ */ diff --git a/samples/server/petstore/cpp-pistache/model/Category.cpp b/samples/server/petstore/cpp-pistache/model/Category.cpp index 489c22157ada..e69de29bb2d1 100644 --- a/samples/server/petstore/cpp-pistache/model/Category.cpp +++ b/samples/server/petstore/cpp-pistache/model/Category.cpp @@ -1,135 +0,0 @@ -/** -* OpenAPI Petstore -* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -* -* The version of the OpenAPI document: 1.0.0 -* -* -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). -* https://openapi-generator.tech -* Do not edit the class manually. -*/ - - -#include "Category.h" -#include "Helpers.h" - -#include - -namespace org::openapitools::server::model -{ - -Category::Category() -{ - m_Id = 0L; - m_IdIsSet = false; - m_Name = ""; - m_NameIsSet = false; - -} - -void Category::validate() const -{ - std::stringstream msg; - if (!validate(msg)) - { - throw org::openapitools::server::helpers::ValidationException(msg.str()); - } -} - -bool Category::validate(std::stringstream& msg) const -{ - return validate(msg, ""); -} - -bool Category::validate(std::stringstream& msg, const std::string& pathPrefix) const -{ - bool success = true; - const std::string _pathPrefix = pathPrefix.empty() ? "Category" : pathPrefix; - - - return success; -} - -bool Category::operator==(const Category& rhs) const -{ - return - - - - ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && - - - ((!nameIsSet() && !rhs.nameIsSet()) || (nameIsSet() && rhs.nameIsSet() && getName() == rhs.getName())) - - ; -} - -bool Category::operator!=(const Category& rhs) const -{ - return !(*this == rhs); -} - -void to_json(nlohmann::json& j, const Category& o) -{ - j = nlohmann::json::object(); - if(o.idIsSet()) - j["id"] = o.m_Id; - if(o.nameIsSet()) - j["name"] = o.m_Name; - -} - -void from_json(const nlohmann::json& j, Category& o) -{ - if(j.find("id") != j.end()) - { - j.at("id").get_to(o.m_Id); - o.m_IdIsSet = true; - } - if(j.find("name") != j.end()) - { - j.at("name").get_to(o.m_Name); - o.m_NameIsSet = true; - } - -} - -int64_t Category::getId() const -{ - return m_Id; -} -void Category::setId(int64_t const value) -{ - m_Id = value; - m_IdIsSet = true; -} -bool Category::idIsSet() const -{ - return m_IdIsSet; -} -void Category::unsetId() -{ - m_IdIsSet = false; -} -std::string Category::getName() const -{ - return m_Name; -} -void Category::setName(std::string const& value) -{ - m_Name = value; - m_NameIsSet = true; -} -bool Category::nameIsSet() const -{ - return m_NameIsSet; -} -void Category::unsetName() -{ - m_NameIsSet = false; -} - - -} // namespace org::openapitools::server::model - From 7ef2004ac94af332f5b7c6fd7c30cdb46841742e Mon Sep 17 00:00:00 2001 From: William Cheng Date: Fri, 13 Feb 2026 15:14:08 +0800 Subject: [PATCH 4/5] update samples --- .../docs/Bird.md | 8 +- .../docs/Category.md | 8 +- .../docs/DataQuery.md | 8 +- .../docs/DefaultValue.md | 8 +- .../docs/NumberPropertiesOnly.md | 8 +- .../docs/Pet.md | 8 +- .../docs/Query.md | 8 +- .../docs/Tag.md | 8 +- .../TestFormObjectMultipartRequestMarker.md | 8 +- ...lodeTrueObjectAllOfQueryObjectParameter.md | 8 +- ...lodeTrueArrayStringQueryObjectParameter.md | 8 +- .../openapi_client/api_client.py | 2 +- .../openapi_client/models/bird.py | 66 +- .../openapi_client/models/category.py | 66 +- .../openapi_client/models/data_query.py | 69 +- .../openapi_client/models/default_value.py | 94 +- .../models/number_properties_only.py | 67 +- .../openapi_client/models/pet.py | 87 +- .../openapi_client/models/query.py | 55 +- .../openapi_client/models/tag.py | 66 +- ...st_form_object_multipart_request_marker.py | 65 +- ...ue_object_all_of_query_object_parameter.py | 68 +- ...rue_array_string_query_object_parameter.py | 65 +- samples/client/echo_api/python/docs/Bird.md | 8 +- .../client/echo_api/python/docs/Category.md | 8 +- .../client/echo_api/python/docs/DataQuery.md | 8 +- .../echo_api/python/docs/DefaultValue.md | 8 +- .../python/docs/NumberPropertiesOnly.md | 8 +- samples/client/echo_api/python/docs/Pet.md | 8 +- samples/client/echo_api/python/docs/Query.md | 8 +- samples/client/echo_api/python/docs/Tag.md | 8 +- .../TestFormObjectMultipartRequestMarker.md | 8 +- ...lodeTrueObjectAllOfQueryObjectParameter.md | 8 +- ...lodeTrueArrayStringQueryObjectParameter.md | 8 +- .../python/openapi_client/api_client.py | 2 +- .../python/openapi_client/models/bird.py | 61 +- .../python/openapi_client/models/category.py | 61 +- .../openapi_client/models/data_query.py | 64 +- .../openapi_client/models/default_value.py | 89 +- .../models/number_properties_only.py | 62 +- .../python/openapi_client/models/pet.py | 82 +- .../python/openapi_client/models/query.py | 55 +- .../python/openapi_client/models/tag.py | 61 +- ...st_form_object_multipart_request_marker.py | 60 +- ...ue_object_all_of_query_object_parameter.py | 63 +- ...rue_array_string_query_object_parameter.py | 60 +- samples/client/others/c/bearerAuth/README.md | 2 +- .../client/others/c/bearerAuth/model/object.c | 51 + .../petstore/ada/.openapi-generator/VERSION | 2 +- .../src/client/samples-petstore-clients.adb | 2 +- .../src/client/samples-petstore-clients.ads | 2 +- .../ada/src/model/samples-petstore-models.adb | 2 +- .../ada/src/model/samples-petstore-models.ads | 2 +- .../petstore/apex/.openapi-generator/VERSION | 2 +- samples/client/petstore/bash/docs/MapTest.md | 13 + samples/client/petstore/bash/docs/Name.md | 13 + .../petstore/c-useJsonUnformatted/model/pet.c | 335 +++++ samples/client/petstore/c/model/category.c | 113 ++ .../petstore/cpp-oatpp/api/StoreApi.hpp | 77 ++ .../client/PFXApiResponse.cpp | 160 +++ .../docs/AdditionalPropertiesAnyType.md | 8 +- .../docs/AdditionalPropertiesClass.md | 8 +- .../docs/AdditionalPropertiesObject.md | 8 +- ...AdditionalPropertiesWithDescriptionOnly.md | 8 +- .../python-aiohttp/docs/AllOfSuperModel.md | 8 +- .../python-aiohttp/docs/AllOfWithSingleRef.md | 8 +- .../petstore/python-aiohttp/docs/Animal.md | 8 +- .../python-aiohttp/docs/AnyOfColor.md | 8 +- .../petstore/python-aiohttp/docs/AnyOfPig.md | 8 +- .../docs/ArrayOfArrayOfModel.md | 8 +- .../docs/ArrayOfArrayOfNumberOnly.md | 8 +- .../python-aiohttp/docs/ArrayOfNumberOnly.md | 8 +- .../petstore/python-aiohttp/docs/ArrayTest.md | 8 +- .../python-aiohttp/docs/BaseDiscriminator.md | 8 +- .../petstore/python-aiohttp/docs/BasquePig.md | 8 +- .../petstore/python-aiohttp/docs/Bathing.md | 8 +- .../python-aiohttp/docs/Capitalization.md | 8 +- .../petstore/python-aiohttp/docs/Cat.md | 8 +- .../petstore/python-aiohttp/docs/Category.md | 8 +- .../python-aiohttp/docs/CircularAllOfRef.md | 8 +- .../docs/CircularReferenceModel.md | 8 +- .../python-aiohttp/docs/ClassModel.md | 8 +- .../petstore/python-aiohttp/docs/Client.md | 8 +- .../petstore/python-aiohttp/docs/Color.md | 8 +- .../petstore/python-aiohttp/docs/Creature.md | 8 +- .../python-aiohttp/docs/CreatureInfo.md | 8 +- .../petstore/python-aiohttp/docs/DanishPig.md | 8 +- .../python-aiohttp/docs/DeprecatedObject.md | 8 +- .../docs/DiscriminatorAllOfSub.md | 8 +- .../docs/DiscriminatorAllOfSuper.md | 8 +- .../petstore/python-aiohttp/docs/Dog.md | 8 +- .../python-aiohttp/docs/DummyModel.md | 8 +- .../python-aiohttp/docs/EnumArrays.md | 8 +- .../docs/EnumRefWithDefaultValue.md | 8 +- .../petstore/python-aiohttp/docs/EnumTest.md | 8 +- .../petstore/python-aiohttp/docs/Feeding.md | 8 +- .../petstore/python-aiohttp/docs/File.md | 8 +- .../docs/FileSchemaTestClass.md | 8 +- .../petstore/python-aiohttp/docs/FirstRef.md | 8 +- .../petstore/python-aiohttp/docs/Foo.md | 8 +- .../docs/FooGetDefaultResponse.md | 8 +- .../python-aiohttp/docs/FormatTest.md | 8 +- .../python-aiohttp/docs/HasOnlyReadOnly.md | 8 +- .../python-aiohttp/docs/HealthCheckResult.md | 8 +- .../python-aiohttp/docs/HuntingDog.md | 8 +- .../petstore/python-aiohttp/docs/Info.md | 8 +- .../docs/InnerDictWithProperty.md | 8 +- .../python-aiohttp/docs/InputAllOf.md | 8 +- .../python-aiohttp/docs/IntOrString.md | 8 +- .../petstore/python-aiohttp/docs/ListClass.md | 8 +- .../python-aiohttp/docs/MapOfArrayOfModel.md | 8 +- .../petstore/python-aiohttp/docs/MapTest.md | 8 +- ...dPropertiesAndAdditionalPropertiesClass.md | 8 +- .../python-aiohttp/docs/Model200Response.md | 8 +- .../python-aiohttp/docs/ModelApiResponse.md | 8 +- .../python-aiohttp/docs/ModelField.md | 8 +- .../python-aiohttp/docs/ModelReturn.md | 8 +- .../python-aiohttp/docs/MultiArrays.md | 8 +- .../petstore/python-aiohttp/docs/Name.md | 8 +- .../python-aiohttp/docs/NullableClass.md | 8 +- .../python-aiohttp/docs/NullableProperty.md | 8 +- .../python-aiohttp/docs/NumberOnly.md | 8 +- .../docs/ObjectToTestAdditionalProperties.md | 8 +- .../docs/ObjectWithDeprecatedFields.md | 8 +- .../petstore/python-aiohttp/docs/Order.md | 8 +- .../python-aiohttp/docs/OuterComposite.md | 8 +- .../docs/OuterObjectWithEnumProperty.md | 8 +- .../petstore/python-aiohttp/docs/Parent.md | 8 +- .../docs/ParentWithOptionalDict.md | 8 +- .../petstore/python-aiohttp/docs/Pet.md | 8 +- .../petstore/python-aiohttp/docs/Pig.md | 8 +- .../petstore/python-aiohttp/docs/PonySizes.md | 8 +- .../python-aiohttp/docs/PoopCleaning.md | 8 +- .../python-aiohttp/docs/PrimitiveString.md | 8 +- .../python-aiohttp/docs/PropertyMap.md | 8 +- .../docs/PropertyNameCollision.md | 8 +- .../python-aiohttp/docs/ReadOnlyFirst.md | 8 +- .../docs/SecondCircularAllOfRef.md | 8 +- .../petstore/python-aiohttp/docs/SecondRef.md | 8 +- .../python-aiohttp/docs/SelfReferenceModel.md | 8 +- .../python-aiohttp/docs/SpecialModelName.md | 8 +- .../python-aiohttp/docs/SpecialName.md | 8 +- .../petstore/python-aiohttp/docs/Tag.md | 8 +- .../petstore/python-aiohttp/docs/Task.md | 8 +- .../python-aiohttp/docs/TaskActivity.md | 8 +- .../TestErrorResponsesWithModel400Response.md | 8 +- .../TestErrorResponsesWithModel404Response.md | 8 +- ...lineFreeformAdditionalPropertiesRequest.md | 8 +- .../docs/TestModelWithEnumDefault.md | 8 +- ...ObjectForMultipartRequestsRequestMarker.md | 8 +- .../petstore/python-aiohttp/docs/Tiger.md | 8 +- ...edDictWithAdditionalModelListProperties.md | 8 +- ...dDictWithAdditionalStringListProperties.md | 8 +- ...leWithAdditionalPropertiesRequestObject.md | 8 +- .../petstore/python-aiohttp/docs/User.md | 8 +- .../python-aiohttp/docs/WithNestedOneOf.md | 8 +- .../python-aiohttp/petstore_api/api_client.py | 2 +- .../models/additional_properties_any_type.py | 74 +- .../models/additional_properties_class.py | 61 +- .../models/additional_properties_object.py | 74 +- ...tional_properties_with_description_only.py | 74 +- .../petstore_api/models/all_of_super_model.py | 60 +- .../models/all_of_with_single_ref.py | 61 +- .../petstore_api/models/animal.py | 60 +- .../petstore_api/models/any_of_color.py | 139 +- .../petstore_api/models/any_of_pig.py | 116 +- .../models/array_of_array_of_model.py | 74 +- .../models/array_of_array_of_number_only.py | 60 +- .../models/array_of_number_only.py | 60 +- .../petstore_api/models/array_test.py | 77 +- .../petstore_api/models/base_discriminator.py | 60 +- .../petstore_api/models/basque_pig.py | 61 +- .../petstore_api/models/bathing.py | 74 +- .../petstore_api/models/capitalization.py | 65 +- .../python-aiohttp/petstore_api/models/cat.py | 62 +- .../petstore_api/models/category.py | 61 +- .../models/circular_all_of_ref.py | 70 +- .../models/circular_reference_model.py | 66 +- .../petstore_api/models/class_model.py | 60 +- .../petstore_api/models/client.py | 60 +- .../petstore_api/models/color.py | 147 +- .../petstore_api/models/creature.py | 63 +- .../petstore_api/models/creature_info.py | 60 +- .../petstore_api/models/danish_pig.py | 61 +- .../petstore_api/models/deprecated_object.py | 60 +- .../models/discriminator_all_of_sub.py | 60 +- .../models/discriminator_all_of_super.py | 58 +- .../python-aiohttp/petstore_api/models/dog.py | 62 +- .../petstore_api/models/dummy_model.py | 66 +- .../petstore_api/models/enum_arrays.py | 71 +- .../models/enum_ref_with_default_value.py | 60 +- .../petstore_api/models/enum_test.py | 116 +- .../petstore_api/models/feeding.py | 74 +- .../petstore_api/models/file.py | 60 +- .../models/file_schema_test_class.py | 73 +- .../petstore_api/models/first_ref.py | 66 +- .../python-aiohttp/petstore_api/models/foo.py | 60 +- .../models/foo_get_default_response.py | 65 +- .../petstore_api/models/format_test.py | 76 +- .../petstore_api/models/has_only_read_only.py | 67 +- .../models/health_check_result.py | 67 +- .../petstore_api/models/hunting_dog.py | 67 +- .../petstore_api/models/info.py | 66 +- .../models/inner_dict_with_property.py | 60 +- .../petstore_api/models/input_all_of.py | 74 +- .../petstore_api/models/int_or_string.py | 122 +- .../petstore_api/models/list_class.py | 60 +- .../models/map_of_array_of_model.py | 78 +- .../petstore_api/models/map_test.py | 68 +- ...perties_and_additional_properties_class.py | 76 +- .../petstore_api/models/model200_response.py | 61 +- .../petstore_api/models/model_api_response.py | 62 +- .../petstore_api/models/model_field.py | 60 +- .../petstore_api/models/model_return.py | 60 +- .../petstore_api/models/multi_arrays.py | 77 +- .../petstore_api/models/name.py | 69 +- .../petstore_api/models/nullable_class.py | 141 +- .../petstore_api/models/nullable_property.py | 68 +- .../petstore_api/models/number_only.py | 60 +- .../object_to_test_additional_properties.py | 60 +- .../models/object_with_deprecated_fields.py | 68 +- .../petstore_api/models/order.py | 70 +- .../petstore_api/models/outer_composite.py | 62 +- .../models/outer_object_with_enum_property.py | 68 +- .../petstore_api/models/parent.py | 74 +- .../models/parent_with_optional_dict.py | 74 +- .../python-aiohttp/petstore_api/models/pet.py | 82 +- .../python-aiohttp/petstore_api/models/pig.py | 117 +- .../petstore_api/models/pony_sizes.py | 60 +- .../petstore_api/models/poop_cleaning.py | 74 +- .../petstore_api/models/primitive_string.py | 61 +- .../petstore_api/models/property_map.py | 74 +- .../models/property_name_collision.py | 62 +- .../petstore_api/models/read_only_first.py | 65 +- .../models/second_circular_all_of_ref.py | 70 +- .../petstore_api/models/second_ref.py | 66 +- .../models/self_reference_model.py | 66 +- .../petstore_api/models/special_model_name.py | 60 +- .../petstore_api/models/special_name.py | 72 +- .../python-aiohttp/petstore_api/models/tag.py | 61 +- .../petstore_api/models/task.py | 66 +- .../petstore_api/models/task_activity.py | 127 +- ..._error_responses_with_model400_response.py | 60 +- ..._error_responses_with_model404_response.py | 60 +- ..._freeform_additional_properties_request.py | 74 +- .../models/test_model_with_enum_default.py | 69 +- ...t_for_multipart_requests_request_marker.py | 60 +- .../petstore_api/models/tiger.py | 60 +- ...t_with_additional_model_list_properties.py | 78 +- ..._with_additional_string_list_properties.py | 60 +- ...th_additional_properties_request_object.py | 60 +- .../petstore_api/models/user.py | 67 +- .../petstore_api/models/with_nested_one_of.py | 67 +- .../docs/AdditionalPropertiesAnyType.md | 8 +- .../docs/AdditionalPropertiesClass.md | 8 +- .../docs/AdditionalPropertiesObject.md | 8 +- ...AdditionalPropertiesWithDescriptionOnly.md | 8 +- .../python-httpx/docs/AllOfSuperModel.md | 8 +- .../python-httpx/docs/AllOfWithSingleRef.md | 8 +- .../petstore/python-httpx/docs/Animal.md | 8 +- .../petstore/python-httpx/docs/AnyOfColor.md | 8 +- .../petstore/python-httpx/docs/AnyOfPig.md | 8 +- .../python-httpx/docs/ArrayOfArrayOfModel.md | 8 +- .../docs/ArrayOfArrayOfNumberOnly.md | 8 +- .../python-httpx/docs/ArrayOfNumberOnly.md | 8 +- .../petstore/python-httpx/docs/ArrayTest.md | 8 +- .../python-httpx/docs/BaseDiscriminator.md | 8 +- .../petstore/python-httpx/docs/BasquePig.md | 8 +- .../petstore/python-httpx/docs/Bathing.md | 8 +- .../python-httpx/docs/Capitalization.md | 8 +- .../client/petstore/python-httpx/docs/Cat.md | 8 +- .../petstore/python-httpx/docs/Category.md | 8 +- .../python-httpx/docs/CircularAllOfRef.md | 8 +- .../docs/CircularReferenceModel.md | 8 +- .../petstore/python-httpx/docs/ClassModel.md | 8 +- .../petstore/python-httpx/docs/Client.md | 8 +- .../petstore/python-httpx/docs/Color.md | 8 +- .../petstore/python-httpx/docs/Creature.md | 8 +- .../python-httpx/docs/CreatureInfo.md | 8 +- .../petstore/python-httpx/docs/DanishPig.md | 8 +- .../python-httpx/docs/DeprecatedObject.md | 8 +- .../docs/DiscriminatorAllOfSub.md | 8 +- .../docs/DiscriminatorAllOfSuper.md | 8 +- .../client/petstore/python-httpx/docs/Dog.md | 8 +- .../petstore/python-httpx/docs/DummyModel.md | 8 +- .../petstore/python-httpx/docs/EnumArrays.md | 8 +- .../docs/EnumRefWithDefaultValue.md | 8 +- .../petstore/python-httpx/docs/EnumTest.md | 8 +- .../petstore/python-httpx/docs/Feeding.md | 8 +- .../client/petstore/python-httpx/docs/File.md | 8 +- .../python-httpx/docs/FileSchemaTestClass.md | 8 +- .../petstore/python-httpx/docs/FirstRef.md | 8 +- .../client/petstore/python-httpx/docs/Foo.md | 8 +- .../docs/FooGetDefaultResponse.md | 8 +- .../petstore/python-httpx/docs/FormatTest.md | 8 +- .../python-httpx/docs/HasOnlyReadOnly.md | 8 +- .../python-httpx/docs/HealthCheckResult.md | 8 +- .../petstore/python-httpx/docs/HuntingDog.md | 8 +- .../client/petstore/python-httpx/docs/Info.md | 8 +- .../docs/InnerDictWithProperty.md | 8 +- .../petstore/python-httpx/docs/InputAllOf.md | 8 +- .../petstore/python-httpx/docs/IntOrString.md | 8 +- .../petstore/python-httpx/docs/ListClass.md | 8 +- .../python-httpx/docs/MapOfArrayOfModel.md | 8 +- .../petstore/python-httpx/docs/MapTest.md | 8 +- ...dPropertiesAndAdditionalPropertiesClass.md | 8 +- .../python-httpx/docs/Model200Response.md | 8 +- .../python-httpx/docs/ModelApiResponse.md | 8 +- .../petstore/python-httpx/docs/ModelField.md | 8 +- .../petstore/python-httpx/docs/ModelReturn.md | 8 +- .../petstore/python-httpx/docs/MultiArrays.md | 8 +- .../client/petstore/python-httpx/docs/Name.md | 8 +- .../python-httpx/docs/NullableClass.md | 8 +- .../python-httpx/docs/NullableProperty.md | 8 +- .../petstore/python-httpx/docs/NumberOnly.md | 8 +- .../docs/ObjectToTestAdditionalProperties.md | 8 +- .../docs/ObjectWithDeprecatedFields.md | 8 +- .../petstore/python-httpx/docs/Order.md | 8 +- .../python-httpx/docs/OuterComposite.md | 8 +- .../docs/OuterObjectWithEnumProperty.md | 8 +- .../petstore/python-httpx/docs/Parent.md | 8 +- .../docs/ParentWithOptionalDict.md | 8 +- .../client/petstore/python-httpx/docs/Pet.md | 8 +- .../client/petstore/python-httpx/docs/Pig.md | 8 +- .../petstore/python-httpx/docs/PonySizes.md | 8 +- .../python-httpx/docs/PoopCleaning.md | 8 +- .../python-httpx/docs/PrimitiveString.md | 8 +- .../petstore/python-httpx/docs/PropertyMap.md | 8 +- .../docs/PropertyNameCollision.md | 8 +- .../python-httpx/docs/ReadOnlyFirst.md | 8 +- .../docs/SecondCircularAllOfRef.md | 8 +- .../petstore/python-httpx/docs/SecondRef.md | 8 +- .../python-httpx/docs/SelfReferenceModel.md | 8 +- .../python-httpx/docs/SpecialModelName.md | 8 +- .../petstore/python-httpx/docs/SpecialName.md | 8 +- .../client/petstore/python-httpx/docs/Tag.md | 8 +- .../client/petstore/python-httpx/docs/Task.md | 8 +- .../python-httpx/docs/TaskActivity.md | 8 +- .../TestErrorResponsesWithModel400Response.md | 8 +- .../TestErrorResponsesWithModel404Response.md | 8 +- ...lineFreeformAdditionalPropertiesRequest.md | 8 +- .../docs/TestModelWithEnumDefault.md | 8 +- ...ObjectForMultipartRequestsRequestMarker.md | 8 +- .../petstore/python-httpx/docs/Tiger.md | 8 +- ...edDictWithAdditionalModelListProperties.md | 8 +- ...dDictWithAdditionalStringListProperties.md | 8 +- ...leWithAdditionalPropertiesRequestObject.md | 8 +- .../client/petstore/python-httpx/docs/User.md | 8 +- .../python-httpx/docs/WithNestedOneOf.md | 8 +- .../python-httpx/petstore_api/api_client.py | 2 +- .../models/additional_properties_any_type.py | 74 +- .../models/additional_properties_class.py | 61 +- .../models/additional_properties_object.py | 74 +- ...tional_properties_with_description_only.py | 74 +- .../petstore_api/models/all_of_super_model.py | 60 +- .../models/all_of_with_single_ref.py | 61 +- .../petstore_api/models/animal.py | 60 +- .../petstore_api/models/any_of_color.py | 139 +- .../petstore_api/models/any_of_pig.py | 116 +- .../models/array_of_array_of_model.py | 74 +- .../models/array_of_array_of_number_only.py | 60 +- .../models/array_of_number_only.py | 60 +- .../petstore_api/models/array_test.py | 77 +- .../petstore_api/models/base_discriminator.py | 60 +- .../petstore_api/models/basque_pig.py | 61 +- .../petstore_api/models/bathing.py | 74 +- .../petstore_api/models/capitalization.py | 65 +- .../python-httpx/petstore_api/models/cat.py | 62 +- .../petstore_api/models/category.py | 61 +- .../models/circular_all_of_ref.py | 70 +- .../models/circular_reference_model.py | 66 +- .../petstore_api/models/class_model.py | 60 +- .../petstore_api/models/client.py | 60 +- .../python-httpx/petstore_api/models/color.py | 147 +- .../petstore_api/models/creature.py | 63 +- .../petstore_api/models/creature_info.py | 60 +- .../petstore_api/models/danish_pig.py | 61 +- .../petstore_api/models/deprecated_object.py | 60 +- .../models/discriminator_all_of_sub.py | 60 +- .../models/discriminator_all_of_super.py | 58 +- .../python-httpx/petstore_api/models/dog.py | 62 +- .../petstore_api/models/dummy_model.py | 66 +- .../petstore_api/models/enum_arrays.py | 71 +- .../models/enum_ref_with_default_value.py | 60 +- .../petstore_api/models/enum_test.py | 116 +- .../petstore_api/models/feeding.py | 74 +- .../python-httpx/petstore_api/models/file.py | 60 +- .../models/file_schema_test_class.py | 73 +- .../petstore_api/models/first_ref.py | 66 +- .../python-httpx/petstore_api/models/foo.py | 60 +- .../models/foo_get_default_response.py | 65 +- .../petstore_api/models/format_test.py | 76 +- .../petstore_api/models/has_only_read_only.py | 67 +- .../models/health_check_result.py | 67 +- .../petstore_api/models/hunting_dog.py | 67 +- .../python-httpx/petstore_api/models/info.py | 66 +- .../models/inner_dict_with_property.py | 60 +- .../petstore_api/models/input_all_of.py | 74 +- .../petstore_api/models/int_or_string.py | 122 +- .../petstore_api/models/list_class.py | 60 +- .../models/map_of_array_of_model.py | 78 +- .../petstore_api/models/map_test.py | 68 +- ...perties_and_additional_properties_class.py | 76 +- .../petstore_api/models/model200_response.py | 61 +- .../petstore_api/models/model_api_response.py | 62 +- .../petstore_api/models/model_field.py | 60 +- .../petstore_api/models/model_return.py | 60 +- .../petstore_api/models/multi_arrays.py | 77 +- .../python-httpx/petstore_api/models/name.py | 69 +- .../petstore_api/models/nullable_class.py | 141 +- .../petstore_api/models/nullable_property.py | 68 +- .../petstore_api/models/number_only.py | 60 +- .../object_to_test_additional_properties.py | 60 +- .../models/object_with_deprecated_fields.py | 68 +- .../python-httpx/petstore_api/models/order.py | 70 +- .../petstore_api/models/outer_composite.py | 62 +- .../models/outer_object_with_enum_property.py | 68 +- .../petstore_api/models/parent.py | 74 +- .../models/parent_with_optional_dict.py | 74 +- .../python-httpx/petstore_api/models/pet.py | 82 +- .../python-httpx/petstore_api/models/pig.py | 117 +- .../petstore_api/models/pony_sizes.py | 60 +- .../petstore_api/models/poop_cleaning.py | 74 +- .../petstore_api/models/primitive_string.py | 61 +- .../petstore_api/models/property_map.py | 74 +- .../models/property_name_collision.py | 62 +- .../petstore_api/models/read_only_first.py | 65 +- .../models/second_circular_all_of_ref.py | 70 +- .../petstore_api/models/second_ref.py | 66 +- .../models/self_reference_model.py | 66 +- .../petstore_api/models/special_model_name.py | 60 +- .../petstore_api/models/special_name.py | 72 +- .../python-httpx/petstore_api/models/tag.py | 61 +- .../python-httpx/petstore_api/models/task.py | 66 +- .../petstore_api/models/task_activity.py | 127 +- ..._error_responses_with_model400_response.py | 60 +- ..._error_responses_with_model404_response.py | 60 +- ..._freeform_additional_properties_request.py | 74 +- .../models/test_model_with_enum_default.py | 69 +- ...t_for_multipart_requests_request_marker.py | 60 +- .../python-httpx/petstore_api/models/tiger.py | 60 +- ...t_with_additional_model_list_properties.py | 78 +- ..._with_additional_string_list_properties.py | 60 +- ...th_additional_properties_request_object.py | 60 +- .../python-httpx/petstore_api/models/user.py | 67 +- .../petstore_api/models/with_nested_one_of.py | 67 +- .../docs/AdditionalPropertiesAnyType.md | 8 +- .../docs/AdditionalPropertiesClass.md | 8 +- .../docs/AdditionalPropertiesObject.md | 8 +- ...AdditionalPropertiesWithDescriptionOnly.md | 8 +- .../docs/AllOfSuperModel.md | 8 +- .../docs/AllOfWithSingleRef.md | 8 +- .../python-lazyImports/docs/Animal.md | 8 +- .../python-lazyImports/docs/AnyOfColor.md | 8 +- .../python-lazyImports/docs/AnyOfPig.md | 8 +- .../docs/ArrayOfArrayOfModel.md | 8 +- .../docs/ArrayOfArrayOfNumberOnly.md | 8 +- .../docs/ArrayOfNumberOnly.md | 8 +- .../python-lazyImports/docs/ArrayTest.md | 8 +- .../docs/BaseDiscriminator.md | 8 +- .../python-lazyImports/docs/BasquePig.md | 8 +- .../python-lazyImports/docs/Bathing.md | 8 +- .../python-lazyImports/docs/Capitalization.md | 8 +- .../petstore/python-lazyImports/docs/Cat.md | 8 +- .../python-lazyImports/docs/Category.md | 8 +- .../docs/CircularAllOfRef.md | 8 +- .../docs/CircularReferenceModel.md | 8 +- .../python-lazyImports/docs/ClassModel.md | 8 +- .../python-lazyImports/docs/Client.md | 8 +- .../petstore/python-lazyImports/docs/Color.md | 8 +- .../python-lazyImports/docs/Creature.md | 8 +- .../python-lazyImports/docs/CreatureInfo.md | 8 +- .../python-lazyImports/docs/DanishPig.md | 8 +- .../docs/DeprecatedObject.md | 8 +- .../docs/DiscriminatorAllOfSub.md | 8 +- .../docs/DiscriminatorAllOfSuper.md | 8 +- .../petstore/python-lazyImports/docs/Dog.md | 8 +- .../python-lazyImports/docs/DummyModel.md | 8 +- .../python-lazyImports/docs/EnumArrays.md | 8 +- .../docs/EnumRefWithDefaultValue.md | 8 +- .../python-lazyImports/docs/EnumTest.md | 8 +- .../python-lazyImports/docs/Feeding.md | 8 +- .../petstore/python-lazyImports/docs/File.md | 8 +- .../docs/FileSchemaTestClass.md | 8 +- .../python-lazyImports/docs/FirstRef.md | 8 +- .../petstore/python-lazyImports/docs/Foo.md | 8 +- .../docs/FooGetDefaultResponse.md | 8 +- .../python-lazyImports/docs/FormatTest.md | 8 +- .../docs/HasOnlyReadOnly.md | 8 +- .../docs/HealthCheckResult.md | 8 +- .../python-lazyImports/docs/HuntingDog.md | 8 +- .../petstore/python-lazyImports/docs/Info.md | 8 +- .../docs/InnerDictWithProperty.md | 8 +- .../python-lazyImports/docs/InputAllOf.md | 8 +- .../python-lazyImports/docs/IntOrString.md | 8 +- .../python-lazyImports/docs/ListClass.md | 8 +- .../docs/MapOfArrayOfModel.md | 8 +- .../python-lazyImports/docs/MapTest.md | 8 +- ...dPropertiesAndAdditionalPropertiesClass.md | 8 +- .../docs/Model200Response.md | 8 +- .../docs/ModelApiResponse.md | 8 +- .../python-lazyImports/docs/ModelField.md | 8 +- .../python-lazyImports/docs/ModelReturn.md | 8 +- .../python-lazyImports/docs/MultiArrays.md | 8 +- .../petstore/python-lazyImports/docs/Name.md | 8 +- .../python-lazyImports/docs/NullableClass.md | 8 +- .../docs/NullableProperty.md | 8 +- .../python-lazyImports/docs/NumberOnly.md | 8 +- .../docs/ObjectToTestAdditionalProperties.md | 8 +- .../docs/ObjectWithDeprecatedFields.md | 8 +- .../docs/OneOfEnumString.md | 8 +- .../petstore/python-lazyImports/docs/Order.md | 8 +- .../python-lazyImports/docs/OuterComposite.md | 8 +- .../docs/OuterObjectWithEnumProperty.md | 8 +- .../python-lazyImports/docs/Parent.md | 8 +- .../docs/ParentWithOptionalDict.md | 8 +- .../petstore/python-lazyImports/docs/Pet.md | 8 +- .../petstore/python-lazyImports/docs/Pig.md | 8 +- .../python-lazyImports/docs/PonySizes.md | 8 +- .../python-lazyImports/docs/PoopCleaning.md | 8 +- .../docs/PrimitiveString.md | 8 +- .../python-lazyImports/docs/PropertyMap.md | 8 +- .../docs/PropertyNameCollision.md | 8 +- .../python-lazyImports/docs/ReadOnlyFirst.md | 8 +- .../docs/SecondCircularAllOfRef.md | 8 +- .../python-lazyImports/docs/SecondRef.md | 8 +- .../docs/SelfReferenceModel.md | 8 +- .../docs/SpecialModelName.md | 8 +- .../python-lazyImports/docs/SpecialName.md | 8 +- .../petstore/python-lazyImports/docs/Tag.md | 8 +- .../petstore/python-lazyImports/docs/Task.md | 8 +- .../python-lazyImports/docs/TaskActivity.md | 8 +- .../TestErrorResponsesWithModel400Response.md | 8 +- .../TestErrorResponsesWithModel404Response.md | 8 +- ...lineFreeformAdditionalPropertiesRequest.md | 8 +- .../docs/TestModelWithEnumDefault.md | 8 +- ...ObjectForMultipartRequestsRequestMarker.md | 8 +- .../petstore/python-lazyImports/docs/Tiger.md | 8 +- ...edDictWithAdditionalModelListProperties.md | 8 +- ...dDictWithAdditionalStringListProperties.md | 8 +- ...leWithAdditionalPropertiesRequestObject.md | 8 +- .../petstore/python-lazyImports/docs/User.md | 8 +- .../docs/WithNestedOneOf.md | 8 +- .../petstore_api/api_client.py | 2 +- .../models/additional_properties_any_type.py | 74 +- .../models/additional_properties_class.py | 75 +- .../models/additional_properties_object.py | 74 +- ...tional_properties_with_description_only.py | 74 +- .../petstore_api/models/all_of_super_model.py | 74 +- .../models/all_of_with_single_ref.py | 75 +- .../petstore_api/models/animal.py | 69 +- .../petstore_api/models/any_of_color.py | 139 +- .../petstore_api/models/any_of_pig.py | 116 +- .../models/array_of_array_of_model.py | 86 +- .../models/array_of_array_of_number_only.py | 74 +- .../models/array_of_number_only.py | 74 +- .../petstore_api/models/array_test.py | 89 +- .../petstore_api/models/base_discriminator.py | 69 +- .../petstore_api/models/basque_pig.py | 75 +- .../petstore_api/models/bathing.py | 88 +- .../petstore_api/models/capitalization.py | 79 +- .../petstore_api/models/cat.py | 76 +- .../petstore_api/models/category.py | 75 +- .../models/circular_all_of_ref.py | 82 +- .../models/circular_reference_model.py | 78 +- .../petstore_api/models/class_model.py | 74 +- .../petstore_api/models/client.py | 74 +- .../petstore_api/models/color.py | 147 +- .../petstore_api/models/creature.py | 70 +- .../petstore_api/models/creature_info.py | 74 +- .../petstore_api/models/danish_pig.py | 75 +- .../petstore_api/models/deprecated_object.py | 74 +- .../models/discriminator_all_of_sub.py | 74 +- .../models/discriminator_all_of_super.py | 67 +- .../petstore_api/models/dog.py | 76 +- .../petstore_api/models/dummy_model.py | 78 +- .../petstore_api/models/enum_arrays.py | 85 +- .../models/enum_ref_with_default_value.py | 74 +- .../petstore_api/models/enum_test.py | 128 +- .../petstore_api/models/feeding.py | 88 +- .../petstore_api/models/file.py | 74 +- .../models/file_schema_test_class.py | 85 +- .../petstore_api/models/first_ref.py | 78 +- .../petstore_api/models/foo.py | 74 +- .../models/foo_get_default_response.py | 77 +- .../petstore_api/models/format_test.py | 90 +- .../petstore_api/models/has_only_read_only.py | 79 +- .../models/health_check_result.py | 79 +- .../petstore_api/models/hunting_dog.py | 79 +- .../petstore_api/models/info.py | 78 +- .../models/inner_dict_with_property.py | 74 +- .../petstore_api/models/input_all_of.py | 86 +- .../petstore_api/models/int_or_string.py | 122 +- .../petstore_api/models/list_class.py | 74 +- .../models/map_of_array_of_model.py | 90 +- .../petstore_api/models/map_test.py | 82 +- ...perties_and_additional_properties_class.py | 88 +- .../petstore_api/models/model200_response.py | 75 +- .../petstore_api/models/model_api_response.py | 76 +- .../petstore_api/models/model_field.py | 74 +- .../petstore_api/models/model_return.py | 74 +- .../petstore_api/models/multi_arrays.py | 89 +- .../petstore_api/models/name.py | 81 +- .../petstore_api/models/nullable_class.py | 141 +- .../petstore_api/models/nullable_property.py | 80 +- .../petstore_api/models/number_only.py | 74 +- .../object_to_test_additional_properties.py | 74 +- .../models/object_with_deprecated_fields.py | 80 +- .../petstore_api/models/one_of_enum_string.py | 114 +- .../petstore_api/models/order.py | 84 +- .../petstore_api/models/outer_composite.py | 76 +- .../models/outer_object_with_enum_property.py | 80 +- .../petstore_api/models/parent.py | 86 +- .../models/parent_with_optional_dict.py | 86 +- .../petstore_api/models/pet.py | 94 +- .../petstore_api/models/pig.py | 132 +- .../petstore_api/models/pony_sizes.py | 74 +- .../petstore_api/models/poop_cleaning.py | 88 +- .../petstore_api/models/primitive_string.py | 75 +- .../petstore_api/models/property_map.py | 86 +- .../models/property_name_collision.py | 76 +- .../petstore_api/models/read_only_first.py | 77 +- .../models/second_circular_all_of_ref.py | 82 +- .../petstore_api/models/second_ref.py | 78 +- .../models/self_reference_model.py | 78 +- .../petstore_api/models/special_model_name.py | 74 +- .../petstore_api/models/special_name.py | 84 +- .../petstore_api/models/tag.py | 75 +- .../petstore_api/models/task.py | 78 +- .../petstore_api/models/task_activity.py | 127 +- ..._error_responses_with_model400_response.py | 74 +- ..._error_responses_with_model404_response.py | 74 +- ..._freeform_additional_properties_request.py | 74 +- .../models/test_model_with_enum_default.py | 83 +- ...t_for_multipart_requests_request_marker.py | 74 +- .../petstore_api/models/tiger.py | 74 +- ...t_with_additional_model_list_properties.py | 90 +- ..._with_additional_string_list_properties.py | 74 +- ...th_additional_properties_request_object.py | 74 +- .../petstore_api/models/user.py | 81 +- .../petstore_api/models/with_nested_one_of.py | 82 +- .../docs/AdditionalPropertiesAnyType.md | 8 +- .../python/docs/AdditionalPropertiesClass.md | 8 +- .../python/docs/AdditionalPropertiesObject.md | 8 +- ...AdditionalPropertiesWithDescriptionOnly.md | 8 +- .../petstore/python/docs/AllOfSuperModel.md | 8 +- .../python/docs/AllOfWithSingleRef.md | 8 +- .../client/petstore/python/docs/Animal.md | 8 +- .../client/petstore/python/docs/AnyOfColor.md | 8 +- .../client/petstore/python/docs/AnyOfPig.md | 8 +- .../python/docs/ArrayOfArrayOfModel.md | 8 +- .../python/docs/ArrayOfArrayOfNumberOnly.md | 8 +- .../petstore/python/docs/ArrayOfNumberOnly.md | 8 +- .../client/petstore/python/docs/ArrayTest.md | 8 +- .../petstore/python/docs/BaseDiscriminator.md | 8 +- .../client/petstore/python/docs/BasquePig.md | 8 +- .../client/petstore/python/docs/Bathing.md | 8 +- .../petstore/python/docs/Capitalization.md | 8 +- .../client/petstore/python/docs/Cat.md | 8 +- .../client/petstore/python/docs/Category.md | 8 +- .../petstore/python/docs/CircularAllOfRef.md | 8 +- .../python/docs/CircularReferenceModel.md | 8 +- .../client/petstore/python/docs/ClassModel.md | 8 +- .../client/petstore/python/docs/Client.md | 8 +- .../client/petstore/python/docs/Color.md | 8 +- .../client/petstore/python/docs/Creature.md | 8 +- .../petstore/python/docs/CreatureInfo.md | 8 +- .../client/petstore/python/docs/DanishPig.md | 8 +- .../petstore/python/docs/DeprecatedObject.md | 8 +- .../python/docs/DiscriminatorAllOfSub.md | 8 +- .../python/docs/DiscriminatorAllOfSuper.md | 8 +- .../client/petstore/python/docs/Dog.md | 8 +- .../client/petstore/python/docs/DummyModel.md | 8 +- .../client/petstore/python/docs/EnumArrays.md | 8 +- .../python/docs/EnumRefWithDefaultValue.md | 8 +- .../client/petstore/python/docs/EnumTest.md | 8 +- .../client/petstore/python/docs/Feeding.md | 8 +- .../client/petstore/python/docs/File.md | 8 +- .../python/docs/FileSchemaTestClass.md | 8 +- .../client/petstore/python/docs/FirstRef.md | 8 +- .../client/petstore/python/docs/Foo.md | 8 +- .../python/docs/FooGetDefaultResponse.md | 8 +- .../client/petstore/python/docs/FormatTest.md | 8 +- .../petstore/python/docs/HasOnlyReadOnly.md | 8 +- .../petstore/python/docs/HealthCheckResult.md | 8 +- .../client/petstore/python/docs/HuntingDog.md | 8 +- .../client/petstore/python/docs/Info.md | 8 +- .../python/docs/InnerDictWithProperty.md | 8 +- .../client/petstore/python/docs/InputAllOf.md | 8 +- .../petstore/python/docs/IntOrString.md | 8 +- .../client/petstore/python/docs/ListClass.md | 8 +- .../petstore/python/docs/MapOfArrayOfModel.md | 8 +- .../client/petstore/python/docs/MapTest.md | 8 +- ...dPropertiesAndAdditionalPropertiesClass.md | 8 +- .../petstore/python/docs/Model200Response.md | 8 +- .../petstore/python/docs/ModelApiResponse.md | 8 +- .../client/petstore/python/docs/ModelField.md | 8 +- .../petstore/python/docs/ModelReturn.md | 8 +- .../petstore/python/docs/MultiArrays.md | 8 +- .../client/petstore/python/docs/Name.md | 8 +- .../petstore/python/docs/NullableClass.md | 8 +- .../petstore/python/docs/NullableProperty.md | 8 +- .../client/petstore/python/docs/NumberOnly.md | 8 +- .../docs/ObjectToTestAdditionalProperties.md | 8 +- .../python/docs/ObjectWithDeprecatedFields.md | 8 +- .../petstore/python/docs/OneOfEnumString.md | 8 +- .../client/petstore/python/docs/Order.md | 8 +- .../petstore/python/docs/OuterComposite.md | 8 +- .../docs/OuterObjectWithEnumProperty.md | 8 +- .../client/petstore/python/docs/Parent.md | 8 +- .../python/docs/ParentWithOptionalDict.md | 8 +- .../client/petstore/python/docs/Pet.md | 8 +- .../client/petstore/python/docs/Pig.md | 8 +- .../client/petstore/python/docs/PonySizes.md | 8 +- .../petstore/python/docs/PoopCleaning.md | 8 +- .../petstore/python/docs/PrimitiveString.md | 8 +- .../petstore/python/docs/PropertyMap.md | 8 +- .../python/docs/PropertyNameCollision.md | 8 +- .../petstore/python/docs/ReadOnlyFirst.md | 8 +- .../python/docs/SecondCircularAllOfRef.md | 8 +- .../client/petstore/python/docs/SecondRef.md | 8 +- .../python/docs/SelfReferenceModel.md | 8 +- .../petstore/python/docs/SpecialModelName.md | 8 +- .../petstore/python/docs/SpecialName.md | 8 +- .../client/petstore/python/docs/Tag.md | 8 +- .../client/petstore/python/docs/Task.md | 8 +- .../petstore/python/docs/TaskActivity.md | 8 +- .../TestErrorResponsesWithModel400Response.md | 8 +- .../TestErrorResponsesWithModel404Response.md | 8 +- ...lineFreeformAdditionalPropertiesRequest.md | 8 +- .../python/docs/TestModelWithEnumDefault.md | 8 +- ...ObjectForMultipartRequestsRequestMarker.md | 8 +- .../client/petstore/python/docs/Tiger.md | 8 +- ...edDictWithAdditionalModelListProperties.md | 8 +- ...dDictWithAdditionalStringListProperties.md | 8 +- ...leWithAdditionalPropertiesRequestObject.md | 8 +- .../client/petstore/python/docs/User.md | 8 +- .../petstore/python/docs/WithNestedOneOf.md | 8 +- .../python/petstore_api/api_client.py | 2 +- .../models/additional_properties_any_type.py | 74 +- .../models/additional_properties_class.py | 75 +- .../models/additional_properties_object.py | 74 +- ...tional_properties_with_description_only.py | 74 +- .../petstore_api/models/all_of_super_model.py | 74 +- .../models/all_of_with_single_ref.py | 75 +- .../python/petstore_api/models/animal.py | 69 +- .../petstore_api/models/any_of_color.py | 139 +- .../python/petstore_api/models/any_of_pig.py | 116 +- .../models/array_of_array_of_model.py | 86 +- .../models/array_of_array_of_number_only.py | 74 +- .../models/array_of_number_only.py | 74 +- .../python/petstore_api/models/array_test.py | 89 +- .../petstore_api/models/base_discriminator.py | 69 +- .../python/petstore_api/models/basque_pig.py | 75 +- .../python/petstore_api/models/bathing.py | 88 +- .../petstore_api/models/capitalization.py | 79 +- .../python/petstore_api/models/cat.py | 76 +- .../python/petstore_api/models/category.py | 75 +- .../models/circular_all_of_ref.py | 82 +- .../models/circular_reference_model.py | 78 +- .../python/petstore_api/models/class_model.py | 74 +- .../python/petstore_api/models/client.py | 74 +- .../python/petstore_api/models/color.py | 147 +- .../python/petstore_api/models/creature.py | 70 +- .../petstore_api/models/creature_info.py | 74 +- .../python/petstore_api/models/danish_pig.py | 75 +- .../petstore_api/models/deprecated_object.py | 74 +- .../models/discriminator_all_of_sub.py | 74 +- .../models/discriminator_all_of_super.py | 67 +- .../python/petstore_api/models/dog.py | 76 +- .../python/petstore_api/models/dummy_model.py | 78 +- .../python/petstore_api/models/enum_arrays.py | 85 +- .../models/enum_ref_with_default_value.py | 74 +- .../python/petstore_api/models/enum_test.py | 128 +- .../python/petstore_api/models/feeding.py | 88 +- .../python/petstore_api/models/file.py | 74 +- .../models/file_schema_test_class.py | 85 +- .../python/petstore_api/models/first_ref.py | 78 +- .../python/petstore_api/models/foo.py | 74 +- .../models/foo_get_default_response.py | 77 +- .../python/petstore_api/models/format_test.py | 90 +- .../petstore_api/models/has_only_read_only.py | 79 +- .../models/health_check_result.py | 79 +- .../python/petstore_api/models/hunting_dog.py | 79 +- .../python/petstore_api/models/info.py | 78 +- .../models/inner_dict_with_property.py | 74 +- .../petstore_api/models/input_all_of.py | 86 +- .../petstore_api/models/int_or_string.py | 122 +- .../python/petstore_api/models/list_class.py | 74 +- .../models/map_of_array_of_model.py | 90 +- .../python/petstore_api/models/map_test.py | 82 +- ...perties_and_additional_properties_class.py | 88 +- .../petstore_api/models/model200_response.py | 75 +- .../petstore_api/models/model_api_response.py | 76 +- .../python/petstore_api/models/model_field.py | 74 +- .../petstore_api/models/model_return.py | 74 +- .../petstore_api/models/multi_arrays.py | 89 +- .../python/petstore_api/models/name.py | 81 +- .../petstore_api/models/nullable_class.py | 141 +- .../petstore_api/models/nullable_property.py | 80 +- .../python/petstore_api/models/number_only.py | 74 +- .../object_to_test_additional_properties.py | 74 +- .../models/object_with_deprecated_fields.py | 80 +- .../petstore_api/models/one_of_enum_string.py | 114 +- .../python/petstore_api/models/order.py | 84 +- .../petstore_api/models/outer_composite.py | 76 +- .../models/outer_object_with_enum_property.py | 80 +- .../python/petstore_api/models/parent.py | 86 +- .../models/parent_with_optional_dict.py | 86 +- .../python/petstore_api/models/pet.py | 94 +- .../python/petstore_api/models/pig.py | 132 +- .../python/petstore_api/models/pony_sizes.py | 74 +- .../petstore_api/models/poop_cleaning.py | 88 +- .../petstore_api/models/primitive_string.py | 75 +- .../petstore_api/models/property_map.py | 86 +- .../models/property_name_collision.py | 76 +- .../petstore_api/models/read_only_first.py | 77 +- .../models/second_circular_all_of_ref.py | 82 +- .../python/petstore_api/models/second_ref.py | 78 +- .../models/self_reference_model.py | 78 +- .../petstore_api/models/special_model_name.py | 74 +- .../petstore_api/models/special_name.py | 84 +- .../python/petstore_api/models/tag.py | 75 +- .../python/petstore_api/models/task.py | 78 +- .../petstore_api/models/task_activity.py | 127 +- ..._error_responses_with_model400_response.py | 74 +- ..._error_responses_with_model404_response.py | 74 +- ..._freeform_additional_properties_request.py | 74 +- .../models/test_model_with_enum_default.py | 83 +- ...t_for_multipart_requests_request_marker.py | 74 +- .../python/petstore_api/models/tiger.py | 74 +- ...t_with_additional_model_list_properties.py | 90 +- ..._with_additional_string_list_properties.py | 74 +- ...th_additional_properties_request_object.py | 74 +- .../python/petstore_api/models/user.py | 81 +- .../petstore_api/models/with_nested_one_of.py | 82 +- .../.openapi-generator/VERSION | 2 +- .../avro-schema/.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../.openapi-generator/VERSION | 2 +- .../fastendpoints/.openapi-generator/VERSION | 2 +- .../GeneratePathParamsValidationFilter.cs | 107 ++ .../GeneratePathParamsValidationFilter.cs | 107 ++ .../Filters/BasePathFilter.cs | 60 + .../GeneratePathParamsValidationFilter.cs | 107 ++ .../GeneratePathParamsValidationFilter.cs | 107 ++ .../GeneratePathParamsValidationFilter.cs | 107 ++ .../wwwroot/openapi-original.json | 1203 +++++++++++++++++ .../.openapi-generator/VERSION | 2 +- .../GeneratePathParamsValidationFilter.cs | 107 ++ .../GeneratePathParamsValidationFilter.cs | 107 ++ .../GeneratePathParamsValidationFilter.cs | 107 ++ .../wwwroot/openapi-original.json | 1203 +++++++++++++++++ .../wwwroot/openapi-original.json | 1203 +++++++++++++++++ .../GeneratePathParamsValidationFilter.cs | 107 ++ .../.openapi-generator/VERSION | 2 +- .../GeneratePathParamsValidationFilter.cs | 107 ++ .../wwwroot/openapi-original.json | 1021 ++++++++++++++ .../server/petstore/cpp-oatpp/model/Order.hpp | 59 + .../server/petstore/cpp-oatpp/model/Tag.hpp | 51 + .../cpp-pistache-everything/model/Order.cpp | 251 ++++ .../api/StoreApi.cpp | 103 ++ .../petstore/cpp-pistache/model/Category.cpp | 135 ++ 868 files changed, 16978 insertions(+), 24707 deletions(-) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Bird.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Bird.md index e61d8458c978..b288e5d280c3 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Bird.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Bird.md @@ -16,14 +16,14 @@ from openapi_client.models.bird import Bird # TODO update the JSON string below json = "{}" # create an instance of Bird from a JSON string -bird_instance = Bird.from_json(json) +bird_instance = Bird.model_validate_json(json) # print the JSON string representation of the object -print(Bird.to_json()) +print(bird_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -bird_dict = bird_instance.to_dict() +bird_dict = bird_instance.model_dump(by_alias=True) # create an instance of Bird from a dict -bird_from_dict = Bird.from_dict(bird_dict) +bird_from_dict = Bird.model_validate(bird_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Category.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Category.md index 9a807466f62a..ca4428075dc4 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Category.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Category.md @@ -16,14 +16,14 @@ from openapi_client.models.category import Category # TODO update the JSON string below json = "{}" # create an instance of Category from a JSON string -category_instance = Category.from_json(json) +category_instance = Category.model_validate_json(json) # print the JSON string representation of the object -print(Category.to_json()) +print(category_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -category_dict = category_instance.to_dict() +category_dict = category_instance.model_dump(by_alias=True) # create an instance of Category from a dict -category_from_dict = Category.from_dict(category_dict) +category_from_dict = Category.model_validate(category_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/DataQuery.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/DataQuery.md index 7ea37bfd23e1..662bd88a9bec 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/DataQuery.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/DataQuery.md @@ -17,14 +17,14 @@ from openapi_client.models.data_query import DataQuery # TODO update the JSON string below json = "{}" # create an instance of DataQuery from a JSON string -data_query_instance = DataQuery.from_json(json) +data_query_instance = DataQuery.model_validate_json(json) # print the JSON string representation of the object -print(DataQuery.to_json()) +print(data_query_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -data_query_dict = data_query_instance.to_dict() +data_query_dict = data_query_instance.model_dump(by_alias=True) # create an instance of DataQuery from a dict -data_query_from_dict = DataQuery.from_dict(data_query_dict) +data_query_from_dict = DataQuery.model_validate(data_query_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/DefaultValue.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/DefaultValue.md index 7c1668c0d6c6..a2a4d3703f37 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/DefaultValue.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/DefaultValue.md @@ -23,14 +23,14 @@ from openapi_client.models.default_value import DefaultValue # TODO update the JSON string below json = "{}" # create an instance of DefaultValue from a JSON string -default_value_instance = DefaultValue.from_json(json) +default_value_instance = DefaultValue.model_validate_json(json) # print the JSON string representation of the object -print(DefaultValue.to_json()) +print(default_value_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -default_value_dict = default_value_instance.to_dict() +default_value_dict = default_value_instance.model_dump(by_alias=True) # create an instance of DefaultValue from a dict -default_value_from_dict = DefaultValue.from_dict(default_value_dict) +default_value_from_dict = DefaultValue.model_validate(default_value_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/NumberPropertiesOnly.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/NumberPropertiesOnly.md index 1f9cb5a1f634..f1883e65d024 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/NumberPropertiesOnly.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/NumberPropertiesOnly.md @@ -17,14 +17,14 @@ from openapi_client.models.number_properties_only import NumberPropertiesOnly # TODO update the JSON string below json = "{}" # create an instance of NumberPropertiesOnly from a JSON string -number_properties_only_instance = NumberPropertiesOnly.from_json(json) +number_properties_only_instance = NumberPropertiesOnly.model_validate_json(json) # print the JSON string representation of the object -print(NumberPropertiesOnly.to_json()) +print(number_properties_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -number_properties_only_dict = number_properties_only_instance.to_dict() +number_properties_only_dict = number_properties_only_instance.model_dump(by_alias=True) # create an instance of NumberPropertiesOnly from a dict -number_properties_only_from_dict = NumberPropertiesOnly.from_dict(number_properties_only_dict) +number_properties_only_from_dict = NumberPropertiesOnly.model_validate(number_properties_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Pet.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Pet.md index 99b4bf3ab010..026ef653d443 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Pet.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Pet.md @@ -20,14 +20,14 @@ from openapi_client.models.pet import Pet # TODO update the JSON string below json = "{}" # create an instance of Pet from a JSON string -pet_instance = Pet.from_json(json) +pet_instance = Pet.model_validate_json(json) # print the JSON string representation of the object -print(Pet.to_json()) +print(pet_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pet_dict = pet_instance.to_dict() +pet_dict = pet_instance.model_dump(by_alias=True) # create an instance of Pet from a dict -pet_from_dict = Pet.from_dict(pet_dict) +pet_from_dict = Pet.model_validate(pet_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Query.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Query.md index d39693eb5b93..c72cdf145b32 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Query.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Query.md @@ -16,14 +16,14 @@ from openapi_client.models.query import Query # TODO update the JSON string below json = "{}" # create an instance of Query from a JSON string -query_instance = Query.from_json(json) +query_instance = Query.model_validate_json(json) # print the JSON string representation of the object -print(Query.to_json()) +print(query_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -query_dict = query_instance.to_dict() +query_dict = query_instance.model_dump(by_alias=True) # create an instance of Query from a dict -query_from_dict = Query.from_dict(query_dict) +query_from_dict = Query.model_validate(query_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Tag.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Tag.md index 21314992cf43..3abb8b678e2c 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Tag.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/Tag.md @@ -16,14 +16,14 @@ from openapi_client.models.tag import Tag # TODO update the JSON string below json = "{}" # create an instance of Tag from a JSON string -tag_instance = Tag.from_json(json) +tag_instance = Tag.model_validate_json(json) # print the JSON string representation of the object -print(Tag.to_json()) +print(tag_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tag_dict = tag_instance.to_dict() +tag_dict = tag_instance.model_dump(by_alias=True) # create an instance of Tag from a dict -tag_from_dict = Tag.from_dict(tag_dict) +tag_from_dict = Tag.model_validate(tag_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestFormObjectMultipartRequestMarker.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestFormObjectMultipartRequestMarker.md index bf4046eb4648..0c5dee4f8f69 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestFormObjectMultipartRequestMarker.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestFormObjectMultipartRequestMarker.md @@ -15,14 +15,14 @@ from openapi_client.models.test_form_object_multipart_request_marker import Test # TODO update the JSON string below json = "{}" # create an instance of TestFormObjectMultipartRequestMarker from a JSON string -test_form_object_multipart_request_marker_instance = TestFormObjectMultipartRequestMarker.from_json(json) +test_form_object_multipart_request_marker_instance = TestFormObjectMultipartRequestMarker.model_validate_json(json) # print the JSON string representation of the object -print(TestFormObjectMultipartRequestMarker.to_json()) +print(test_form_object_multipart_request_marker_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_form_object_multipart_request_marker_dict = test_form_object_multipart_request_marker_instance.to_dict() +test_form_object_multipart_request_marker_dict = test_form_object_multipart_request_marker_instance.model_dump(by_alias=True) # create an instance of TestFormObjectMultipartRequestMarker from a dict -test_form_object_multipart_request_marker_from_dict = TestFormObjectMultipartRequestMarker.from_dict(test_form_object_multipart_request_marker_dict) +test_form_object_multipart_request_marker_from_dict = TestFormObjectMultipartRequestMarker.model_validate(test_form_object_multipart_request_marker_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md index 96c36ca12e0f..9cda4fca20c8 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md @@ -18,14 +18,14 @@ from openapi_client.models.test_query_style_deep_object_explode_true_object_all_ # TODO update the JSON string below json = "{}" # create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a JSON string -test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance = TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.from_json(json) +test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance = TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.model_validate_json(json) # print the JSON string representation of the object -print(TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.to_json()) +print(test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_dict = test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance.to_dict() +test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_dict = test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance.model_dump(by_alias=True) # create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a dict -test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_from_dict = TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.from_dict(test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_dict) +test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_from_dict = TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.model_validate(test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md index 846a0941a09c..6af94f3aed1a 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md @@ -15,14 +15,14 @@ from openapi_client.models.test_query_style_form_explode_true_array_string_query # TODO update the JSON string below json = "{}" # create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a JSON string -test_query_style_form_explode_true_array_string_query_object_parameter_instance = TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.from_json(json) +test_query_style_form_explode_true_array_string_query_object_parameter_instance = TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.model_validate_json(json) # print the JSON string representation of the object -print(TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.to_json()) +print(test_query_style_form_explode_true_array_string_query_object_parameter_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_query_style_form_explode_true_array_string_query_object_parameter_dict = test_query_style_form_explode_true_array_string_query_object_parameter_instance.to_dict() +test_query_style_form_explode_true_array_string_query_object_parameter_dict = test_query_style_form_explode_true_array_string_query_object_parameter_instance.model_dump(by_alias=True) # create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a dict -test_query_style_form_explode_true_array_string_query_object_parameter_from_dict = TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.from_dict(test_query_style_form_explode_true_array_string_query_object_parameter_dict) +test_query_style_form_explode_true_array_string_query_object_parameter_from_dict = TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.model_validate(test_query_style_form_explode_true_array_string_query_object_parameter_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/api_client.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/api_client.py index 5de92b6c6705..4c9fd74258fd 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/api_client.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/api_client.py @@ -708,7 +708,7 @@ def __deserialize_file(self, response): content_disposition ) assert m is not None, "Unexpected 'content-disposition' header value" - filename = m.group(1) + filename = os.path.basename(m.group(1)) # Strip any directory traversal path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/bird.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/bird.py index 9bb24b9e6d80..ebd8db839b9d 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/bird.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/bird.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Bird(BaseModel): """ @@ -38,58 +39,27 @@ class Bird(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Bird from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Bird from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in Bird) in the input: " + _key) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "color": obj.get("color") - }) - return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/category.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/category.py index c8e9bb709fd1..0141a70c25b9 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/category.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/category.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Category(BaseModel): """ @@ -38,58 +39,27 @@ class Category(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Category from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Category from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in Category) in the input: " + _key) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/data_query.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/data_query.py index 255a5ab7f422..6cb8e9db3792 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/data_query.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/data_query.py @@ -23,7 +23,8 @@ from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.query import Query from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DataQuery(Query): """ @@ -41,61 +42,27 @@ class DataQuery(Query): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DataQuery from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DataQuery from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DataQuery) in the input: " + _key) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "outcomes": obj.get("outcomes"), - "suffix": obj.get("suffix"), - "text": obj.get("text"), - "date": obj.get("date") - }) - return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/default_value.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/default_value.py index 8dceac31e3d5..fa9fb5b73053 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/default_value.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/default_value.py @@ -22,14 +22,18 @@ from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.string_enum_ref import StringEnumRef from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DefaultValue(BaseModel): """ to test the default value of properties """ # noqa: E501 array_string_enum_ref_default: Optional[List[StringEnumRef]] = None - array_string_enum_default: Optional[List[StrictStr]] = None + array_string_enum_default: Optional[List[Literal['success', 'failure', 'unclassified']]] = Field( + None, + description="array_string_enum_default of the DefaultValue" + ) array_string_default: Optional[List[StrictStr]] = None array_integer_default: Optional[List[StrictInt]] = None array_string: Optional[List[StrictStr]] = None @@ -56,79 +60,27 @@ def array_string_enum_default_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DefaultValue from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if array_string_nullable (nullable) is None - # and model_fields_set contains the field - if self.array_string_nullable is None and "array_string_nullable" in self.model_fields_set: - _dict['array_string_nullable'] = None - - # set to None if array_string_extension_nullable (nullable) is None - # and model_fields_set contains the field - if self.array_string_extension_nullable is None and "array_string_extension_nullable" in self.model_fields_set: - _dict['array_string_extension_nullable'] = None - - # set to None if string_nullable (nullable) is None - # and model_fields_set contains the field - if self.string_nullable is None and "string_nullable" in self.model_fields_set: - _dict['string_nullable'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DefaultValue from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in DefaultValue) in the input: " + _key) - - _obj = cls.model_validate({ - "array_string_enum_ref_default": obj.get("array_string_enum_ref_default"), - "array_string_enum_default": obj.get("array_string_enum_default"), - "array_string_default": obj.get("array_string_default"), - "array_integer_default": obj.get("array_integer_default"), - "array_string": obj.get("array_string"), - "array_string_nullable": obj.get("array_string_nullable"), - "array_string_extension_nullable": obj.get("array_string_extension_nullable"), - "string_nullable": obj.get("string_nullable") - }) - return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/number_properties_only.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/number_properties_only.py index d089c9775ace..060b52f1eb3f 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/number_properties_only.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/number_properties_only.py @@ -22,7 +22,8 @@ from typing import Any, ClassVar, Dict, List, Optional, Union from typing_extensions import Annotated from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NumberPropertiesOnly(BaseModel): """ @@ -40,59 +41,27 @@ class NumberPropertiesOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NumberPropertiesOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NumberPropertiesOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in NumberPropertiesOnly) in the input: " + _key) - - _obj = cls.model_validate({ - "number": obj.get("number"), - "float": obj.get("float"), - "double": obj.get("double") - }) - return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/pet.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/pet.py index bfe90956d977..549afb23ba27 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/pet.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/pet.py @@ -23,7 +23,8 @@ from openapi_client.models.category import Category from openapi_client.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Pet(BaseModel): """ @@ -34,7 +35,10 @@ class Pet(BaseModel): category: Optional[Category] = None photo_urls: List[StrictStr] = Field(alias="photoUrls") tags: Optional[List[Tag]] = None - status: Optional[StrictStr] = Field(default=None, description="pet status in the store") + status: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) __properties: ClassVar[List[str]] = ["id", "name", "category", "photoUrls", "tags", "status"] @field_validator('status') @@ -54,72 +58,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Pet from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of category - if self.category: - _dict['category'] = self.category.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Pet from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in Pet) in the input: " + _key) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name"), - "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, - "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "status": obj.get("status") - }) - return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/query.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/query.py index 97199fb7fd95..d85397784ab6 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/query.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/query.py @@ -21,14 +21,18 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Query(BaseModel): """ Query """ # noqa: E501 id: Optional[StrictInt] = Field(default=None, description="Query") - outcomes: Optional[List[StrictStr]] = None + outcomes: Optional[List[Literal['SUCCESS', 'FAILURE', 'SKIPPED']]] = Field( + None, + description="outcomes of the Query" + ) __properties: ClassVar[List[str]] = ["id", "outcomes"] @field_validator('outcomes') @@ -49,42 +53,27 @@ def outcomes_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Query from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Self]: - """Create an instance of Query from a dict""" diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/tag.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/tag.py index 5ec177ca73ae..dfa3f138a05f 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/tag.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/tag.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tag(BaseModel): """ @@ -38,58 +39,27 @@ class Tag(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tag from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tag from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in Tag) in the input: " + _key) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_form_object_multipart_request_marker.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_form_object_multipart_request_marker.py index 9fab70ea178d..eb314e3aade6 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_form_object_multipart_request_marker.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_form_object_multipart_request_marker.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestFormObjectMultipartRequestMarker(BaseModel): """ @@ -37,57 +38,27 @@ class TestFormObjectMultipartRequestMarker(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestFormObjectMultipartRequestMarker from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestFormObjectMultipartRequestMarker from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TestFormObjectMultipartRequestMarker) in the input: " + _key) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py index 8cf292b6a90b..afc081b08336 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(BaseModel): """ @@ -40,60 +41,27 @@ class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(BaseMod ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter) in the input: " + _key) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "color": obj.get("color"), - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py index 726b427743ca..8cb2bd25be30 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(BaseModel): """ @@ -37,57 +38,27 @@ class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - # raise errors for additional fields in the input - for _key in obj.keys(): - if _key not in cls.__properties: - raise ValueError("Error due to additional fields (not defined in TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter) in the input: " + _key) - - _obj = cls.model_validate({ - "values": obj.get("values") - }) - return _obj diff --git a/samples/client/echo_api/python/docs/Bird.md b/samples/client/echo_api/python/docs/Bird.md index e61d8458c978..b288e5d280c3 100644 --- a/samples/client/echo_api/python/docs/Bird.md +++ b/samples/client/echo_api/python/docs/Bird.md @@ -16,14 +16,14 @@ from openapi_client.models.bird import Bird # TODO update the JSON string below json = "{}" # create an instance of Bird from a JSON string -bird_instance = Bird.from_json(json) +bird_instance = Bird.model_validate_json(json) # print the JSON string representation of the object -print(Bird.to_json()) +print(bird_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -bird_dict = bird_instance.to_dict() +bird_dict = bird_instance.model_dump(by_alias=True) # create an instance of Bird from a dict -bird_from_dict = Bird.from_dict(bird_dict) +bird_from_dict = Bird.model_validate(bird_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/Category.md b/samples/client/echo_api/python/docs/Category.md index 9a807466f62a..ca4428075dc4 100644 --- a/samples/client/echo_api/python/docs/Category.md +++ b/samples/client/echo_api/python/docs/Category.md @@ -16,14 +16,14 @@ from openapi_client.models.category import Category # TODO update the JSON string below json = "{}" # create an instance of Category from a JSON string -category_instance = Category.from_json(json) +category_instance = Category.model_validate_json(json) # print the JSON string representation of the object -print(Category.to_json()) +print(category_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -category_dict = category_instance.to_dict() +category_dict = category_instance.model_dump(by_alias=True) # create an instance of Category from a dict -category_from_dict = Category.from_dict(category_dict) +category_from_dict = Category.model_validate(category_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/DataQuery.md b/samples/client/echo_api/python/docs/DataQuery.md index 7ea37bfd23e1..662bd88a9bec 100644 --- a/samples/client/echo_api/python/docs/DataQuery.md +++ b/samples/client/echo_api/python/docs/DataQuery.md @@ -17,14 +17,14 @@ from openapi_client.models.data_query import DataQuery # TODO update the JSON string below json = "{}" # create an instance of DataQuery from a JSON string -data_query_instance = DataQuery.from_json(json) +data_query_instance = DataQuery.model_validate_json(json) # print the JSON string representation of the object -print(DataQuery.to_json()) +print(data_query_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -data_query_dict = data_query_instance.to_dict() +data_query_dict = data_query_instance.model_dump(by_alias=True) # create an instance of DataQuery from a dict -data_query_from_dict = DataQuery.from_dict(data_query_dict) +data_query_from_dict = DataQuery.model_validate(data_query_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/DefaultValue.md b/samples/client/echo_api/python/docs/DefaultValue.md index 7c1668c0d6c6..a2a4d3703f37 100644 --- a/samples/client/echo_api/python/docs/DefaultValue.md +++ b/samples/client/echo_api/python/docs/DefaultValue.md @@ -23,14 +23,14 @@ from openapi_client.models.default_value import DefaultValue # TODO update the JSON string below json = "{}" # create an instance of DefaultValue from a JSON string -default_value_instance = DefaultValue.from_json(json) +default_value_instance = DefaultValue.model_validate_json(json) # print the JSON string representation of the object -print(DefaultValue.to_json()) +print(default_value_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -default_value_dict = default_value_instance.to_dict() +default_value_dict = default_value_instance.model_dump(by_alias=True) # create an instance of DefaultValue from a dict -default_value_from_dict = DefaultValue.from_dict(default_value_dict) +default_value_from_dict = DefaultValue.model_validate(default_value_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/NumberPropertiesOnly.md b/samples/client/echo_api/python/docs/NumberPropertiesOnly.md index 1f9cb5a1f634..f1883e65d024 100644 --- a/samples/client/echo_api/python/docs/NumberPropertiesOnly.md +++ b/samples/client/echo_api/python/docs/NumberPropertiesOnly.md @@ -17,14 +17,14 @@ from openapi_client.models.number_properties_only import NumberPropertiesOnly # TODO update the JSON string below json = "{}" # create an instance of NumberPropertiesOnly from a JSON string -number_properties_only_instance = NumberPropertiesOnly.from_json(json) +number_properties_only_instance = NumberPropertiesOnly.model_validate_json(json) # print the JSON string representation of the object -print(NumberPropertiesOnly.to_json()) +print(number_properties_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -number_properties_only_dict = number_properties_only_instance.to_dict() +number_properties_only_dict = number_properties_only_instance.model_dump(by_alias=True) # create an instance of NumberPropertiesOnly from a dict -number_properties_only_from_dict = NumberPropertiesOnly.from_dict(number_properties_only_dict) +number_properties_only_from_dict = NumberPropertiesOnly.model_validate(number_properties_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/Pet.md b/samples/client/echo_api/python/docs/Pet.md index 99b4bf3ab010..026ef653d443 100644 --- a/samples/client/echo_api/python/docs/Pet.md +++ b/samples/client/echo_api/python/docs/Pet.md @@ -20,14 +20,14 @@ from openapi_client.models.pet import Pet # TODO update the JSON string below json = "{}" # create an instance of Pet from a JSON string -pet_instance = Pet.from_json(json) +pet_instance = Pet.model_validate_json(json) # print the JSON string representation of the object -print(Pet.to_json()) +print(pet_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pet_dict = pet_instance.to_dict() +pet_dict = pet_instance.model_dump(by_alias=True) # create an instance of Pet from a dict -pet_from_dict = Pet.from_dict(pet_dict) +pet_from_dict = Pet.model_validate(pet_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/Query.md b/samples/client/echo_api/python/docs/Query.md index d39693eb5b93..c72cdf145b32 100644 --- a/samples/client/echo_api/python/docs/Query.md +++ b/samples/client/echo_api/python/docs/Query.md @@ -16,14 +16,14 @@ from openapi_client.models.query import Query # TODO update the JSON string below json = "{}" # create an instance of Query from a JSON string -query_instance = Query.from_json(json) +query_instance = Query.model_validate_json(json) # print the JSON string representation of the object -print(Query.to_json()) +print(query_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -query_dict = query_instance.to_dict() +query_dict = query_instance.model_dump(by_alias=True) # create an instance of Query from a dict -query_from_dict = Query.from_dict(query_dict) +query_from_dict = Query.model_validate(query_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/Tag.md b/samples/client/echo_api/python/docs/Tag.md index 21314992cf43..3abb8b678e2c 100644 --- a/samples/client/echo_api/python/docs/Tag.md +++ b/samples/client/echo_api/python/docs/Tag.md @@ -16,14 +16,14 @@ from openapi_client.models.tag import Tag # TODO update the JSON string below json = "{}" # create an instance of Tag from a JSON string -tag_instance = Tag.from_json(json) +tag_instance = Tag.model_validate_json(json) # print the JSON string representation of the object -print(Tag.to_json()) +print(tag_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tag_dict = tag_instance.to_dict() +tag_dict = tag_instance.model_dump(by_alias=True) # create an instance of Tag from a dict -tag_from_dict = Tag.from_dict(tag_dict) +tag_from_dict = Tag.model_validate(tag_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/TestFormObjectMultipartRequestMarker.md b/samples/client/echo_api/python/docs/TestFormObjectMultipartRequestMarker.md index bf4046eb4648..0c5dee4f8f69 100644 --- a/samples/client/echo_api/python/docs/TestFormObjectMultipartRequestMarker.md +++ b/samples/client/echo_api/python/docs/TestFormObjectMultipartRequestMarker.md @@ -15,14 +15,14 @@ from openapi_client.models.test_form_object_multipart_request_marker import Test # TODO update the JSON string below json = "{}" # create an instance of TestFormObjectMultipartRequestMarker from a JSON string -test_form_object_multipart_request_marker_instance = TestFormObjectMultipartRequestMarker.from_json(json) +test_form_object_multipart_request_marker_instance = TestFormObjectMultipartRequestMarker.model_validate_json(json) # print the JSON string representation of the object -print(TestFormObjectMultipartRequestMarker.to_json()) +print(test_form_object_multipart_request_marker_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_form_object_multipart_request_marker_dict = test_form_object_multipart_request_marker_instance.to_dict() +test_form_object_multipart_request_marker_dict = test_form_object_multipart_request_marker_instance.model_dump(by_alias=True) # create an instance of TestFormObjectMultipartRequestMarker from a dict -test_form_object_multipart_request_marker_from_dict = TestFormObjectMultipartRequestMarker.from_dict(test_form_object_multipart_request_marker_dict) +test_form_object_multipart_request_marker_from_dict = TestFormObjectMultipartRequestMarker.model_validate(test_form_object_multipart_request_marker_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md b/samples/client/echo_api/python/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md index 96c36ca12e0f..9cda4fca20c8 100644 --- a/samples/client/echo_api/python/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md +++ b/samples/client/echo_api/python/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md @@ -18,14 +18,14 @@ from openapi_client.models.test_query_style_deep_object_explode_true_object_all_ # TODO update the JSON string below json = "{}" # create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a JSON string -test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance = TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.from_json(json) +test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance = TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.model_validate_json(json) # print the JSON string representation of the object -print(TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.to_json()) +print(test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_dict = test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance.to_dict() +test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_dict = test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_instance.model_dump(by_alias=True) # create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a dict -test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_from_dict = TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.from_dict(test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_dict) +test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_from_dict = TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.model_validate(test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md b/samples/client/echo_api/python/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md index 846a0941a09c..6af94f3aed1a 100644 --- a/samples/client/echo_api/python/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md +++ b/samples/client/echo_api/python/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md @@ -15,14 +15,14 @@ from openapi_client.models.test_query_style_form_explode_true_array_string_query # TODO update the JSON string below json = "{}" # create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a JSON string -test_query_style_form_explode_true_array_string_query_object_parameter_instance = TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.from_json(json) +test_query_style_form_explode_true_array_string_query_object_parameter_instance = TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.model_validate_json(json) # print the JSON string representation of the object -print(TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.to_json()) +print(test_query_style_form_explode_true_array_string_query_object_parameter_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_query_style_form_explode_true_array_string_query_object_parameter_dict = test_query_style_form_explode_true_array_string_query_object_parameter_instance.to_dict() +test_query_style_form_explode_true_array_string_query_object_parameter_dict = test_query_style_form_explode_true_array_string_query_object_parameter_instance.model_dump(by_alias=True) # create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a dict -test_query_style_form_explode_true_array_string_query_object_parameter_from_dict = TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.from_dict(test_query_style_form_explode_true_array_string_query_object_parameter_dict) +test_query_style_form_explode_true_array_string_query_object_parameter_from_dict = TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.model_validate(test_query_style_form_explode_true_array_string_query_object_parameter_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/echo_api/python/openapi_client/api_client.py b/samples/client/echo_api/python/openapi_client/api_client.py index 5de92b6c6705..4c9fd74258fd 100644 --- a/samples/client/echo_api/python/openapi_client/api_client.py +++ b/samples/client/echo_api/python/openapi_client/api_client.py @@ -708,7 +708,7 @@ def __deserialize_file(self, response): content_disposition ) assert m is not None, "Unexpected 'content-disposition' header value" - filename = m.group(1) + filename = os.path.basename(m.group(1)) # Strip any directory traversal path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/client/echo_api/python/openapi_client/models/bird.py b/samples/client/echo_api/python/openapi_client/models/bird.py index 9f0dd625119d..ebd8db839b9d 100644 --- a/samples/client/echo_api/python/openapi_client/models/bird.py +++ b/samples/client/echo_api/python/openapi_client/models/bird.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Bird(BaseModel): """ @@ -38,53 +39,27 @@ class Bird(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Bird from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Bird from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "color": obj.get("color") - }) - return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/category.py b/samples/client/echo_api/python/openapi_client/models/category.py index d81b92c0f6e3..0141a70c25b9 100644 --- a/samples/client/echo_api/python/openapi_client/models/category.py +++ b/samples/client/echo_api/python/openapi_client/models/category.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Category(BaseModel): """ @@ -38,53 +39,27 @@ class Category(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Category from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Category from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/data_query.py b/samples/client/echo_api/python/openapi_client/models/data_query.py index dc9a58598e63..6cb8e9db3792 100644 --- a/samples/client/echo_api/python/openapi_client/models/data_query.py +++ b/samples/client/echo_api/python/openapi_client/models/data_query.py @@ -23,7 +23,8 @@ from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.query import Query from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DataQuery(Query): """ @@ -41,56 +42,27 @@ class DataQuery(Query): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DataQuery from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DataQuery from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "outcomes": obj.get("outcomes"), - "suffix": obj.get("suffix"), - "text": obj.get("text"), - "date": obj.get("date") - }) - return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/default_value.py b/samples/client/echo_api/python/openapi_client/models/default_value.py index feee1843319f..fa9fb5b73053 100644 --- a/samples/client/echo_api/python/openapi_client/models/default_value.py +++ b/samples/client/echo_api/python/openapi_client/models/default_value.py @@ -22,14 +22,18 @@ from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.string_enum_ref import StringEnumRef from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DefaultValue(BaseModel): """ to test the default value of properties """ # noqa: E501 array_string_enum_ref_default: Optional[List[StringEnumRef]] = None - array_string_enum_default: Optional[List[StrictStr]] = None + array_string_enum_default: Optional[List[Literal['success', 'failure', 'unclassified']]] = Field( + None, + description="array_string_enum_default of the DefaultValue" + ) array_string_default: Optional[List[StrictStr]] = None array_integer_default: Optional[List[StrictInt]] = None array_string: Optional[List[StrictStr]] = None @@ -56,74 +60,27 @@ def array_string_enum_default_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DefaultValue from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if array_string_nullable (nullable) is None - # and model_fields_set contains the field - if self.array_string_nullable is None and "array_string_nullable" in self.model_fields_set: - _dict['array_string_nullable'] = None - - # set to None if array_string_extension_nullable (nullable) is None - # and model_fields_set contains the field - if self.array_string_extension_nullable is None and "array_string_extension_nullable" in self.model_fields_set: - _dict['array_string_extension_nullable'] = None - - # set to None if string_nullable (nullable) is None - # and model_fields_set contains the field - if self.string_nullable is None and "string_nullable" in self.model_fields_set: - _dict['string_nullable'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DefaultValue from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "array_string_enum_ref_default": obj.get("array_string_enum_ref_default"), - "array_string_enum_default": obj.get("array_string_enum_default"), - "array_string_default": obj.get("array_string_default"), - "array_integer_default": obj.get("array_integer_default"), - "array_string": obj.get("array_string"), - "array_string_nullable": obj.get("array_string_nullable"), - "array_string_extension_nullable": obj.get("array_string_extension_nullable"), - "string_nullable": obj.get("string_nullable") - }) - return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/number_properties_only.py b/samples/client/echo_api/python/openapi_client/models/number_properties_only.py index 08b3d5600ffa..060b52f1eb3f 100644 --- a/samples/client/echo_api/python/openapi_client/models/number_properties_only.py +++ b/samples/client/echo_api/python/openapi_client/models/number_properties_only.py @@ -22,7 +22,8 @@ from typing import Any, ClassVar, Dict, List, Optional, Union from typing_extensions import Annotated from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NumberPropertiesOnly(BaseModel): """ @@ -40,54 +41,27 @@ class NumberPropertiesOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NumberPropertiesOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NumberPropertiesOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "number": obj.get("number"), - "float": obj.get("float"), - "double": obj.get("double") - }) - return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/pet.py b/samples/client/echo_api/python/openapi_client/models/pet.py index 0a0ae74d1155..549afb23ba27 100644 --- a/samples/client/echo_api/python/openapi_client/models/pet.py +++ b/samples/client/echo_api/python/openapi_client/models/pet.py @@ -23,7 +23,8 @@ from openapi_client.models.category import Category from openapi_client.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Pet(BaseModel): """ @@ -34,7 +35,10 @@ class Pet(BaseModel): category: Optional[Category] = None photo_urls: List[StrictStr] = Field(alias="photoUrls") tags: Optional[List[Tag]] = None - status: Optional[StrictStr] = Field(default=None, description="pet status in the store") + status: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) __properties: ClassVar[List[str]] = ["id", "name", "category", "photoUrls", "tags", "status"] @field_validator('status') @@ -54,67 +58,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Pet from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of category - if self.category: - _dict['category'] = self.category.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Pet from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name"), - "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, - "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "status": obj.get("status") - }) - return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/query.py b/samples/client/echo_api/python/openapi_client/models/query.py index 97199fb7fd95..d85397784ab6 100644 --- a/samples/client/echo_api/python/openapi_client/models/query.py +++ b/samples/client/echo_api/python/openapi_client/models/query.py @@ -21,14 +21,18 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Query(BaseModel): """ Query """ # noqa: E501 id: Optional[StrictInt] = Field(default=None, description="Query") - outcomes: Optional[List[StrictStr]] = None + outcomes: Optional[List[Literal['SUCCESS', 'FAILURE', 'SKIPPED']]] = Field( + None, + description="outcomes of the Query" + ) __properties: ClassVar[List[str]] = ["id", "outcomes"] @field_validator('outcomes') @@ -49,42 +53,27 @@ def outcomes_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Query from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Self]: - """Create an instance of Query from a dict""" diff --git a/samples/client/echo_api/python/openapi_client/models/tag.py b/samples/client/echo_api/python/openapi_client/models/tag.py index feec4b3f31cc..dfa3f138a05f 100644 --- a/samples/client/echo_api/python/openapi_client/models/tag.py +++ b/samples/client/echo_api/python/openapi_client/models/tag.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tag(BaseModel): """ @@ -38,53 +39,27 @@ class Tag(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tag from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tag from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/test_form_object_multipart_request_marker.py b/samples/client/echo_api/python/openapi_client/models/test_form_object_multipart_request_marker.py index 9f7747151bd5..eb314e3aade6 100644 --- a/samples/client/echo_api/python/openapi_client/models/test_form_object_multipart_request_marker.py +++ b/samples/client/echo_api/python/openapi_client/models/test_form_object_multipart_request_marker.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestFormObjectMultipartRequestMarker(BaseModel): """ @@ -37,52 +38,27 @@ class TestFormObjectMultipartRequestMarker(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestFormObjectMultipartRequestMarker from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestFormObjectMultipartRequestMarker from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py b/samples/client/echo_api/python/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py index 8ed0f58c990b..afc081b08336 100644 --- a/samples/client/echo_api/python/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py +++ b/samples/client/echo_api/python/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(BaseModel): """ @@ -40,55 +41,27 @@ class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(BaseMod ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "color": obj.get("color"), - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py b/samples/client/echo_api/python/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py index a9a7a5929f2e..8cb2bd25be30 100644 --- a/samples/client/echo_api/python/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py +++ b/samples/client/echo_api/python/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(BaseModel): """ @@ -37,52 +38,27 @@ class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "values": obj.get("values") - }) - return _obj diff --git a/samples/client/others/c/bearerAuth/README.md b/samples/client/others/c/bearerAuth/README.md index 2875a52718b2..fb04f51e2c7a 100644 --- a/samples/client/others/c/bearerAuth/README.md +++ b/samples/client/others/c/bearerAuth/README.md @@ -5,7 +5,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat - API version: 0.1.9 - Package version: -- Generator version: 7.19.0-SNAPSHOT +- Generator version: 7.20.0-SNAPSHOT - Build package: org.openapitools.codegen.languages.CLibcurlClientCodegen ## Installation diff --git a/samples/client/others/c/bearerAuth/model/object.c b/samples/client/others/c/bearerAuth/model/object.c index e69de29bb2d1..ff293bcdac85 100644 --- a/samples/client/others/c/bearerAuth/model/object.c +++ b/samples/client/others/c/bearerAuth/model/object.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include "object.h" + +object_t *object_create() { + object_t *object = calloc(1, sizeof(object_t)); + + return object; +} + +void object_free(object_t *object) { + if (!object) { + return ; + } + + if (object->temporary) { + free(object->temporary); + object->temporary = NULL; + } + + free (object); +} + +cJSON *object_convertToJSON(object_t *object) { + if (!object) { + return NULL; + } + + if (!object->temporary) { + return cJSON_Parse("null"); + } + + return cJSON_Parse(object->temporary); +} + +object_t *object_parseFromJSON(cJSON *json){ + if (!json) { + goto end; + } + + object_t *object = object_create(); + if (!object) { + goto end; + } + object->temporary = cJSON_Print(json); + return object; + +end: + return NULL; +} diff --git a/samples/client/petstore/ada/.openapi-generator/VERSION b/samples/client/petstore/ada/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/client/petstore/ada/.openapi-generator/VERSION +++ b/samples/client/petstore/ada/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/client/petstore/ada/src/client/samples-petstore-clients.adb b/samples/client/petstore/ada/src/client/samples-petstore-clients.adb index 03cbbb4abc2f..1ae7faf60e86 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-clients.adb +++ b/samples/client/petstore/ada/src/client/samples-petstore-clients.adb @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.19.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.20.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/ada/src/client/samples-petstore-clients.ads b/samples/client/petstore/ada/src/client/samples-petstore-clients.ads index 9939509f8a12..36fa9c1fe37c 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-clients.ads +++ b/samples/client/petstore/ada/src/client/samples-petstore-clients.ads @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.19.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.20.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/ada/src/model/samples-petstore-models.adb b/samples/client/petstore/ada/src/model/samples-petstore-models.adb index 6e96402c2a80..e4a88a95e039 100644 --- a/samples/client/petstore/ada/src/model/samples-petstore-models.adb +++ b/samples/client/petstore/ada/src/model/samples-petstore-models.adb @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.19.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.20.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/ada/src/model/samples-petstore-models.ads b/samples/client/petstore/ada/src/model/samples-petstore-models.ads index 1a72c99d4f72..f4e05c36ca48 100644 --- a/samples/client/petstore/ada/src/model/samples-petstore-models.ads +++ b/samples/client/petstore/ada/src/model/samples-petstore-models.ads @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.19.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.20.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/apex/.openapi-generator/VERSION b/samples/client/petstore/apex/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/client/petstore/apex/.openapi-generator/VERSION +++ b/samples/client/petstore/apex/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/client/petstore/bash/docs/MapTest.md b/samples/client/petstore/bash/docs/MapTest.md index e69de29bb2d1..e4ed4a233829 100644 --- a/samples/client/petstore/bash/docs/MapTest.md +++ b/samples/client/petstore/bash/docs/MapTest.md @@ -0,0 +1,13 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapUnderscoremapUnderscoreofUnderscorestring** | **map[String, map[String, string]]** | | [optional] [default to null] +**mapUnderscoreofUnderscoreenumUnderscorestring** | **map[String, string]** | | [optional] [default to null] +**directUnderscoremap** | **map[String, boolean]** | | [optional] [default to null] +**indirectUnderscoremap** | **map[String, boolean]** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/bash/docs/Name.md b/samples/client/petstore/bash/docs/Name.md index e69de29bb2d1..295812c7bb7e 100644 --- a/samples/client/petstore/bash/docs/Name.md +++ b/samples/client/petstore/bash/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **integer** | | [default to null] +**snakeUnderscorecase** | **integer** | | [optional] [readonly] [default to null] +**property** | **string** | | [optional] [default to null] +**123Number** | **integer** | | [optional] [readonly] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/c-useJsonUnformatted/model/pet.c b/samples/client/petstore/c-useJsonUnformatted/model/pet.c index e69de29bb2d1..b561634cb529 100644 --- a/samples/client/petstore/c-useJsonUnformatted/model/pet.c +++ b/samples/client/petstore/c-useJsonUnformatted/model/pet.c @@ -0,0 +1,335 @@ +#include +#include +#include +#include "pet.h" + + +char* pet_status_ToString(openapi_petstore_pet_STATUS_e status) { + char* statusArray[] = { "NULL", "available", "pending", "sold" }; + return statusArray[status]; +} + +openapi_petstore_pet_STATUS_e pet_status_FromString(char* status){ + int stringToReturn = 0; + char *statusArray[] = { "NULL", "available", "pending", "sold" }; + size_t sizeofArray = sizeof(statusArray) / sizeof(statusArray[0]); + while(stringToReturn < sizeofArray) { + if(strcmp(status, statusArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + +static pet_t *pet_create_internal( + long id, + category_t *category, + char *name, + list_t *photo_urls, + list_t *tags, + openapi_petstore_pet_STATUS_e status + ) { + pet_t *pet_local_var = malloc(sizeof(pet_t)); + if (!pet_local_var) { + return NULL; + } + pet_local_var->id = id; + pet_local_var->category = category; + pet_local_var->name = name; + pet_local_var->photo_urls = photo_urls; + pet_local_var->tags = tags; + pet_local_var->status = status; + + pet_local_var->_library_owned = 1; + return pet_local_var; +} + +__attribute__((deprecated)) pet_t *pet_create( + long id, + category_t *category, + char *name, + list_t *photo_urls, + list_t *tags, + openapi_petstore_pet_STATUS_e status + ) { + return pet_create_internal ( + id, + category, + name, + photo_urls, + tags, + status + ); +} + +void pet_free(pet_t *pet) { + if(NULL == pet){ + return ; + } + if(pet->_library_owned != 1){ + fprintf(stderr, "WARNING: %s() does NOT free objects allocated by the user\n", "pet_free"); + return ; + } + listEntry_t *listEntry; + if (pet->category) { + category_free(pet->category); + pet->category = NULL; + } + if (pet->name) { + free(pet->name); + pet->name = NULL; + } + if (pet->photo_urls) { + list_ForEach(listEntry, pet->photo_urls) { + free(listEntry->data); + } + list_freeList(pet->photo_urls); + pet->photo_urls = NULL; + } + if (pet->tags) { + list_ForEach(listEntry, pet->tags) { + tag_free(listEntry->data); + } + list_freeList(pet->tags); + pet->tags = NULL; + } + free(pet); +} + +cJSON *pet_convertToJSON(pet_t *pet) { + cJSON *item = cJSON_CreateObject(); + + // pet->id + if(pet->id) { + if(cJSON_AddNumberToObject(item, "id", pet->id) == NULL) { + goto fail; //Numeric + } + } + + + // pet->category + if(pet->category) { + cJSON *category_local_JSON = category_convertToJSON(pet->category); + if(category_local_JSON == NULL) { + goto fail; //model + } + cJSON_AddItemToObject(item, "category", category_local_JSON); + if(item->child == NULL) { + goto fail; + } + } + + + // pet->name + if (!pet->name) { + goto fail; + } + if(cJSON_AddStringToObject(item, "name", pet->name) == NULL) { + goto fail; //String + } + + + // pet->photo_urls + if (!pet->photo_urls) { + goto fail; + } + cJSON *photo_urls = cJSON_AddArrayToObject(item, "photoUrls"); + if(photo_urls == NULL) { + goto fail; //primitive container + } + + listEntry_t *photo_urlsListEntry; + list_ForEach(photo_urlsListEntry, pet->photo_urls) { + if(cJSON_AddStringToObject(photo_urls, "", photo_urlsListEntry->data) == NULL) + { + goto fail; + } + } + + + // pet->tags + if(pet->tags) { + cJSON *tags = cJSON_AddArrayToObject(item, "tags"); + if(tags == NULL) { + goto fail; //nonprimitive container + } + + listEntry_t *tagsListEntry; + if (pet->tags) { + list_ForEach(tagsListEntry, pet->tags) { + cJSON *itemLocal = tag_convertToJSON(tagsListEntry->data); + if(itemLocal == NULL) { + goto fail; + } + cJSON_AddItemToArray(tags, itemLocal); + } + } + } + + + // pet->status + if(pet->status != openapi_petstore_pet_STATUS_NULL) { + if(cJSON_AddStringToObject(item, "status", pet_status_ToString(pet->status)) == NULL) + { + goto fail; //Enum + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +pet_t *pet_parseFromJSON(cJSON *petJSON){ + + pet_t *pet_local_var = NULL; + + // define the local variable for pet->category + category_t *category_local_nonprim = NULL; + + // define the local list for pet->photo_urls + list_t *photo_urlsList = NULL; + + // define the local list for pet->tags + list_t *tagsList = NULL; + + // pet->id + cJSON *id = cJSON_GetObjectItemCaseSensitive(petJSON, "id"); + if (cJSON_IsNull(id)) { + id = NULL; + } + if (id) { + if(!cJSON_IsNumber(id)) + { + goto end; //Numeric + } + } + + // pet->category + cJSON *category = cJSON_GetObjectItemCaseSensitive(petJSON, "category"); + if (cJSON_IsNull(category)) { + category = NULL; + } + if (category) { + category_local_nonprim = category_parseFromJSON(category); //nonprimitive + } + + // pet->name + cJSON *name = cJSON_GetObjectItemCaseSensitive(petJSON, "name"); + if (cJSON_IsNull(name)) { + name = NULL; + } + if (!name) { + goto end; + } + + + if(!cJSON_IsString(name)) + { + goto end; //String + } + + // pet->photo_urls + cJSON *photo_urls = cJSON_GetObjectItemCaseSensitive(petJSON, "photoUrls"); + if (cJSON_IsNull(photo_urls)) { + photo_urls = NULL; + } + if (!photo_urls) { + goto end; + } + + + cJSON *photo_urls_local = NULL; + if(!cJSON_IsArray(photo_urls)) { + goto end;//primitive container + } + photo_urlsList = list_createList(); + + cJSON_ArrayForEach(photo_urls_local, photo_urls) + { + if(!cJSON_IsString(photo_urls_local)) + { + goto end; + } + list_addElement(photo_urlsList , strdup(photo_urls_local->valuestring)); + } + + // pet->tags + cJSON *tags = cJSON_GetObjectItemCaseSensitive(petJSON, "tags"); + if (cJSON_IsNull(tags)) { + tags = NULL; + } + if (tags) { + cJSON *tags_local_nonprimitive = NULL; + if(!cJSON_IsArray(tags)){ + goto end; //nonprimitive container + } + + tagsList = list_createList(); + + cJSON_ArrayForEach(tags_local_nonprimitive,tags ) + { + if(!cJSON_IsObject(tags_local_nonprimitive)){ + goto end; + } + tag_t *tagsItem = tag_parseFromJSON(tags_local_nonprimitive); + + list_addElement(tagsList, tagsItem); + } + } + + // pet->status + cJSON *status = cJSON_GetObjectItemCaseSensitive(petJSON, "status"); + if (cJSON_IsNull(status)) { + status = NULL; + } + openapi_petstore_pet_STATUS_e statusVariable; + if (status) { + if(!cJSON_IsString(status)) + { + goto end; //Enum + } + statusVariable = pet_status_FromString(status->valuestring); + } + + + pet_local_var = pet_create_internal ( + id ? id->valuedouble : 0, + category ? category_local_nonprim : NULL, + strdup(name->valuestring), + photo_urlsList, + tags ? tagsList : NULL, + status ? statusVariable : openapi_petstore_pet_STATUS_NULL + ); + + return pet_local_var; +end: + if (category_local_nonprim) { + category_free(category_local_nonprim); + category_local_nonprim = NULL; + } + if (photo_urlsList) { + listEntry_t *listEntry = NULL; + list_ForEach(listEntry, photo_urlsList) { + free(listEntry->data); + listEntry->data = NULL; + } + list_freeList(photo_urlsList); + photo_urlsList = NULL; + } + if (tagsList) { + listEntry_t *listEntry = NULL; + list_ForEach(listEntry, tagsList) { + tag_free(listEntry->data); + listEntry->data = NULL; + } + list_freeList(tagsList); + tagsList = NULL; + } + return NULL; + +} diff --git a/samples/client/petstore/c/model/category.c b/samples/client/petstore/c/model/category.c index e69de29bb2d1..2b060a568015 100644 --- a/samples/client/petstore/c/model/category.c +++ b/samples/client/petstore/c/model/category.c @@ -0,0 +1,113 @@ +#include +#include +#include +#include "category.h" + + + +static category_t *category_create_internal( + long id, + char *name + ) { + category_t *category_local_var = malloc(sizeof(category_t)); + if (!category_local_var) { + return NULL; + } + category_local_var->id = id; + category_local_var->name = name; + + category_local_var->_library_owned = 1; + return category_local_var; +} + +__attribute__((deprecated)) category_t *category_create( + long id, + char *name + ) { + return category_create_internal ( + id, + name + ); +} + +void category_free(category_t *category) { + if(NULL == category){ + return ; + } + if(category->_library_owned != 1){ + fprintf(stderr, "WARNING: %s() does NOT free objects allocated by the user\n", "category_free"); + return ; + } + listEntry_t *listEntry; + if (category->name) { + free(category->name); + category->name = NULL; + } + free(category); +} + +cJSON *category_convertToJSON(category_t *category) { + cJSON *item = cJSON_CreateObject(); + + // category->id + if(category->id) { + if(cJSON_AddNumberToObject(item, "id", category->id) == NULL) { + goto fail; //Numeric + } + } + + + // category->name + if(category->name) { + if(cJSON_AddStringToObject(item, "name", category->name) == NULL) { + goto fail; //String + } + } + + return item; +fail: + if (item) { + cJSON_Delete(item); + } + return NULL; +} + +category_t *category_parseFromJSON(cJSON *categoryJSON){ + + category_t *category_local_var = NULL; + + // category->id + cJSON *id = cJSON_GetObjectItemCaseSensitive(categoryJSON, "id"); + if (cJSON_IsNull(id)) { + id = NULL; + } + if (id) { + if(!cJSON_IsNumber(id)) + { + goto end; //Numeric + } + } + + // category->name + cJSON *name = cJSON_GetObjectItemCaseSensitive(categoryJSON, "name"); + if (cJSON_IsNull(name)) { + name = NULL; + } + if (name) { + if(!cJSON_IsString(name) && !cJSON_IsNull(name)) + { + goto end; //String + } + } + + + category_local_var = category_create_internal ( + id ? id->valuedouble : 0, + name && !cJSON_IsNull(name) ? strdup(name->valuestring) : NULL + ); + + return category_local_var; +end: + return NULL; + +} diff --git a/samples/client/petstore/cpp-oatpp/api/StoreApi.hpp b/samples/client/petstore/cpp-oatpp/api/StoreApi.hpp index e69de29bb2d1..f48ec25ab0ab 100644 --- a/samples/client/petstore/cpp-oatpp/api/StoreApi.hpp +++ b/samples/client/petstore/cpp-oatpp/api/StoreApi.hpp @@ -0,0 +1,77 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +/* + * StoreApi.h + * + * + */ + +#ifndef StoreApi_H_ +#define StoreApi_H_ + + + +#include "oatpp/web/client/ApiClient.hpp" +#include "oatpp/web/protocol/http/outgoing/MultipartBody.hpp" +#include "oatpp/core/macro/codegen.hpp" + +#include "Order.hpp" + +#include OATPP_CODEGEN_BEGIN(ApiClient) ///< Begin code-gen section + +namespace org::openapitools::client::api +{ + +class StoreApi : public oatpp::web::client::ApiClient { +public: + + API_CLIENT_INIT(StoreApi) + + /// + /// Delete purchase order by ID + /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// + /// ID of the order that needs to be deleted + API_CALL("DELETE", "/store/order/{orderId}", delete_order, PATH(oatpp::String, orderId)) + /// + /// Returns pet inventories by status + /// + /// + /// Returns a map of status codes to quantities + /// + API_CALL("GET", "/store/inventory", get_inventory) + /// + /// Find purchase order by ID + /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + /// + /// ID of pet that needs to be fetched + API_CALL("GET", "/store/order/{orderId}", get_order_by_id, PATH(oatpp::Int64, orderId)) + /// + /// Place an order for a pet + /// + /// + /// + /// + /// order placed for purchasing the pet + API_CALL("POST", "/store/order", place_order, BODY_DTO(oatpp::Object, order)) +}; + +#include OATPP_CODEGEN_END(ApiClient) ///< End code-gen section + +} // namespace org::openapitools::client::api + +#endif /* StoreApi_H_ */ + diff --git a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp index e69de29bb2d1..8fbef0fb8c5c 100644 --- a/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp +++ b/samples/client/petstore/cpp-qt-addDownloadProgress/client/PFXApiResponse.cpp @@ -0,0 +1,160 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "PFXApiResponse.h" + +#include +#include +#include +#include + +#include "PFXHelpers.h" + +namespace test_namespace { + +PFXApiResponse::PFXApiResponse(QString json) { + this->initializeModel(); + this->fromJson(json); +} + +PFXApiResponse::PFXApiResponse() { + this->initializeModel(); +} + +PFXApiResponse::~PFXApiResponse() {} + +void PFXApiResponse::initializeModel() { + + m_code_isSet = false; + m_code_isValid = false; + + m_type_isSet = false; + m_type_isValid = false; + + m_message_isSet = false; + m_message_isValid = false; +} + +void PFXApiResponse::fromJson(QString jsonString) { + QByteArray array(jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void PFXApiResponse::fromJsonObject(QJsonObject json) { + + m_code_isValid = ::test_namespace::fromJsonValue(m_code, json[QString("code")]); + m_code_isSet = !json[QString("code")].isNull() && m_code_isValid; + + m_type_isValid = ::test_namespace::fromJsonValue(m_type, json[QString("type")]); + m_type_isSet = !json[QString("type")].isNull() && m_type_isValid; + + m_message_isValid = ::test_namespace::fromJsonValue(m_message, json[QString("message")]); + m_message_isSet = !json[QString("message")].isNull() && m_message_isValid; +} + +QString PFXApiResponse::asJson() const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject PFXApiResponse::asJsonObject() const { + QJsonObject obj; + if (m_code_isSet) { + obj.insert(QString("code"), ::test_namespace::toJsonValue(m_code)); + } + if (m_type_isSet) { + obj.insert(QString("type"), ::test_namespace::toJsonValue(m_type)); + } + if (m_message_isSet) { + obj.insert(QString("message"), ::test_namespace::toJsonValue(m_message)); + } + return obj; +} + +qint32 PFXApiResponse::getCode() const { + return m_code; +} +void PFXApiResponse::setCode(const qint32 &code) { + m_code = code; + m_code_isSet = true; +} + +bool PFXApiResponse::is_code_Set() const{ + return m_code_isSet; +} + +bool PFXApiResponse::is_code_Valid() const{ + return m_code_isValid; +} + +QString PFXApiResponse::getType() const { + return m_type; +} +void PFXApiResponse::setType(const QString &type) { + m_type = type; + m_type_isSet = true; +} + +bool PFXApiResponse::is_type_Set() const{ + return m_type_isSet; +} + +bool PFXApiResponse::is_type_Valid() const{ + return m_type_isValid; +} + +QString PFXApiResponse::getMessage() const { + return m_message; +} +void PFXApiResponse::setMessage(const QString &message) { + m_message = message; + m_message_isSet = true; +} + +bool PFXApiResponse::is_message_Set() const{ + return m_message_isSet; +} + +bool PFXApiResponse::is_message_Valid() const{ + return m_message_isValid; +} + +bool PFXApiResponse::isSet() const { + bool isObjectUpdated = false; + do { + if (m_code_isSet) { + isObjectUpdated = true; + break; + } + + if (m_type_isSet) { + isObjectUpdated = true; + break; + } + + if (m_message_isSet) { + isObjectUpdated = true; + break; + } + } while (false); + return isObjectUpdated; +} + +bool PFXApiResponse::isValid() const { + // only required properties are required for the object to be considered valid + return true; +} + +} // namespace test_namespace diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md index 314cba3a614c..b94c1e6d7d19 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_any_type import AdditionalPropert # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesAnyType from a JSON string -additional_properties_any_type_instance = AdditionalPropertiesAnyType.from_json(json) +additional_properties_any_type_instance = AdditionalPropertiesAnyType.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesAnyType.to_json()) +print(additional_properties_any_type_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_any_type_dict = additional_properties_any_type_instance.to_dict() +additional_properties_any_type_dict = additional_properties_any_type_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesAnyType from a dict -additional_properties_any_type_from_dict = AdditionalPropertiesAnyType.from_dict(additional_properties_any_type_dict) +additional_properties_any_type_from_dict = AdditionalPropertiesAnyType.model_validate(additional_properties_any_type_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesClass.md index 8d4c08707f55..4c880d6853e8 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesClass.md @@ -16,14 +16,14 @@ from petstore_api.models.additional_properties_class import AdditionalProperties # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesClass from a JSON string -additional_properties_class_instance = AdditionalPropertiesClass.from_json(json) +additional_properties_class_instance = AdditionalPropertiesClass.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesClass.to_json()) +print(additional_properties_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_class_dict = additional_properties_class_instance.to_dict() +additional_properties_class_dict = additional_properties_class_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesClass from a dict -additional_properties_class_from_dict = AdditionalPropertiesClass.from_dict(additional_properties_class_dict) +additional_properties_class_from_dict = AdditionalPropertiesClass.model_validate(additional_properties_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md index d647ec64896f..bf6743709338 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_object import AdditionalPropertie # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesObject from a JSON string -additional_properties_object_instance = AdditionalPropertiesObject.from_json(json) +additional_properties_object_instance = AdditionalPropertiesObject.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesObject.to_json()) +print(additional_properties_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_object_dict = additional_properties_object_instance.to_dict() +additional_properties_object_dict = additional_properties_object_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesObject from a dict -additional_properties_object_from_dict = AdditionalPropertiesObject.from_dict(additional_properties_object_dict) +additional_properties_object_from_dict = AdditionalPropertiesObject.model_validate(additional_properties_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md index 061f5524872b..1cb2a02f7584 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_with_description_only import Addi # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string -additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.from_json(json) +additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesWithDescriptionOnly.to_json()) +print(additional_properties_with_description_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.to_dict() +additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesWithDescriptionOnly from a dict -additional_properties_with_description_only_from_dict = AdditionalPropertiesWithDescriptionOnly.from_dict(additional_properties_with_description_only_dict) +additional_properties_with_description_only_from_dict = AdditionalPropertiesWithDescriptionOnly.model_validate(additional_properties_with_description_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfSuperModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfSuperModel.md index 421a1527f1ef..88cb95097517 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfSuperModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfSuperModel.md @@ -15,14 +15,14 @@ from petstore_api.models.all_of_super_model import AllOfSuperModel # TODO update the JSON string below json = "{}" # create an instance of AllOfSuperModel from a JSON string -all_of_super_model_instance = AllOfSuperModel.from_json(json) +all_of_super_model_instance = AllOfSuperModel.model_validate_json(json) # print the JSON string representation of the object -print(AllOfSuperModel.to_json()) +print(all_of_super_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -all_of_super_model_dict = all_of_super_model_instance.to_dict() +all_of_super_model_dict = all_of_super_model_instance.model_dump(by_alias=True) # create an instance of AllOfSuperModel from a dict -all_of_super_model_from_dict = AllOfSuperModel.from_dict(all_of_super_model_dict) +all_of_super_model_from_dict = AllOfSuperModel.model_validate(all_of_super_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfWithSingleRef.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfWithSingleRef.md index 203a4b5da3d5..dd0f755dfe65 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfWithSingleRef.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfWithSingleRef.md @@ -16,14 +16,14 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef # TODO update the JSON string below json = "{}" # create an instance of AllOfWithSingleRef from a JSON string -all_of_with_single_ref_instance = AllOfWithSingleRef.from_json(json) +all_of_with_single_ref_instance = AllOfWithSingleRef.model_validate_json(json) # print the JSON string representation of the object -print(AllOfWithSingleRef.to_json()) +print(all_of_with_single_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -all_of_with_single_ref_dict = all_of_with_single_ref_instance.to_dict() +all_of_with_single_ref_dict = all_of_with_single_ref_instance.model_dump(by_alias=True) # create an instance of AllOfWithSingleRef from a dict -all_of_with_single_ref_from_dict = AllOfWithSingleRef.from_dict(all_of_with_single_ref_dict) +all_of_with_single_ref_from_dict = AllOfWithSingleRef.model_validate(all_of_with_single_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Animal.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Animal.md index 381d27b66e44..fcded75f52be 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Animal.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Animal.md @@ -16,14 +16,14 @@ from petstore_api.models.animal import Animal # TODO update the JSON string below json = "{}" # create an instance of Animal from a JSON string -animal_instance = Animal.from_json(json) +animal_instance = Animal.model_validate_json(json) # print the JSON string representation of the object -print(Animal.to_json()) +print(animal_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -animal_dict = animal_instance.to_dict() +animal_dict = animal_instance.model_dump(by_alias=True) # create an instance of Animal from a dict -animal_from_dict = Animal.from_dict(animal_dict) +animal_from_dict = Animal.model_validate(animal_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfColor.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfColor.md index 6ed75dd7b48a..02aab883b2b0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfColor.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfColor.md @@ -15,14 +15,14 @@ from petstore_api.models.any_of_color import AnyOfColor # TODO update the JSON string below json = "{}" # create an instance of AnyOfColor from a JSON string -any_of_color_instance = AnyOfColor.from_json(json) +any_of_color_instance = AnyOfColor.model_validate_json(json) # print the JSON string representation of the object -print(AnyOfColor.to_json()) +print(any_of_color_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -any_of_color_dict = any_of_color_instance.to_dict() +any_of_color_dict = any_of_color_instance.model_dump(by_alias=True) # create an instance of AnyOfColor from a dict -any_of_color_from_dict = AnyOfColor.from_dict(any_of_color_dict) +any_of_color_from_dict = AnyOfColor.model_validate(any_of_color_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfPig.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfPig.md index 9367e2261898..db2878121f29 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfPig.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfPig.md @@ -17,14 +17,14 @@ from petstore_api.models.any_of_pig import AnyOfPig # TODO update the JSON string below json = "{}" # create an instance of AnyOfPig from a JSON string -any_of_pig_instance = AnyOfPig.from_json(json) +any_of_pig_instance = AnyOfPig.model_validate_json(json) # print the JSON string representation of the object -print(AnyOfPig.to_json()) +print(any_of_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -any_of_pig_dict = any_of_pig_instance.to_dict() +any_of_pig_dict = any_of_pig_instance.model_dump(by_alias=True) # create an instance of AnyOfPig from a dict -any_of_pig_from_dict = AnyOfPig.from_dict(any_of_pig_dict) +any_of_pig_from_dict = AnyOfPig.model_validate(any_of_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfModel.md index f866863d53f9..e8274d8fbb52 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfModel.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel # TODO update the JSON string below json = "{}" # create an instance of ArrayOfArrayOfModel from a JSON string -array_of_array_of_model_instance = ArrayOfArrayOfModel.from_json(json) +array_of_array_of_model_instance = ArrayOfArrayOfModel.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfArrayOfModel.to_json()) +print(array_of_array_of_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_array_of_model_dict = array_of_array_of_model_instance.to_dict() +array_of_array_of_model_dict = array_of_array_of_model_instance.model_dump(by_alias=True) # create an instance of ArrayOfArrayOfModel from a dict -array_of_array_of_model_from_dict = ArrayOfArrayOfModel.from_dict(array_of_array_of_model_dict) +array_of_array_of_model_from_dict = ArrayOfArrayOfModel.model_validate(array_of_array_of_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfNumberOnly.md index 32bd2dfbf1e2..8931a1c7e467 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfNumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumb # TODO update the JSON string below json = "{}" # create an instance of ArrayOfArrayOfNumberOnly from a JSON string -array_of_array_of_number_only_instance = ArrayOfArrayOfNumberOnly.from_json(json) +array_of_array_of_number_only_instance = ArrayOfArrayOfNumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfArrayOfNumberOnly.to_json()) +print(array_of_array_of_number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_array_of_number_only_dict = array_of_array_of_number_only_instance.to_dict() +array_of_array_of_number_only_dict = array_of_array_of_number_only_instance.model_dump(by_alias=True) # create an instance of ArrayOfArrayOfNumberOnly from a dict -array_of_array_of_number_only_from_dict = ArrayOfArrayOfNumberOnly.from_dict(array_of_array_of_number_only_dict) +array_of_array_of_number_only_from_dict = ArrayOfArrayOfNumberOnly.model_validate(array_of_array_of_number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfNumberOnly.md index b814d7594942..a709583be699 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfNumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly # TODO update the JSON string below json = "{}" # create an instance of ArrayOfNumberOnly from a JSON string -array_of_number_only_instance = ArrayOfNumberOnly.from_json(json) +array_of_number_only_instance = ArrayOfNumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfNumberOnly.to_json()) +print(array_of_number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_number_only_dict = array_of_number_only_instance.to_dict() +array_of_number_only_dict = array_of_number_only_instance.model_dump(by_alias=True) # create an instance of ArrayOfNumberOnly from a dict -array_of_number_only_from_dict = ArrayOfNumberOnly.from_dict(array_of_number_only_dict) +array_of_number_only_from_dict = ArrayOfNumberOnly.model_validate(array_of_number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayTest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayTest.md index ed871fae662d..a99eb056c5ca 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayTest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayTest.md @@ -18,14 +18,14 @@ from petstore_api.models.array_test import ArrayTest # TODO update the JSON string below json = "{}" # create an instance of ArrayTest from a JSON string -array_test_instance = ArrayTest.from_json(json) +array_test_instance = ArrayTest.model_validate_json(json) # print the JSON string representation of the object -print(ArrayTest.to_json()) +print(array_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_test_dict = array_test_instance.to_dict() +array_test_dict = array_test_instance.model_dump(by_alias=True) # create an instance of ArrayTest from a dict -array_test_from_dict = ArrayTest.from_dict(array_test_dict) +array_test_from_dict = ArrayTest.model_validate(array_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/BaseDiscriminator.md b/samples/openapi3/client/petstore/python-aiohttp/docs/BaseDiscriminator.md index fcdbeb032e68..0482396cbcf8 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/BaseDiscriminator.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/BaseDiscriminator.md @@ -15,14 +15,14 @@ from petstore_api.models.base_discriminator import BaseDiscriminator # TODO update the JSON string below json = "{}" # create an instance of BaseDiscriminator from a JSON string -base_discriminator_instance = BaseDiscriminator.from_json(json) +base_discriminator_instance = BaseDiscriminator.model_validate_json(json) # print the JSON string representation of the object -print(BaseDiscriminator.to_json()) +print(base_discriminator_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -base_discriminator_dict = base_discriminator_instance.to_dict() +base_discriminator_dict = base_discriminator_instance.model_dump(by_alias=True) # create an instance of BaseDiscriminator from a dict -base_discriminator_from_dict = BaseDiscriminator.from_dict(base_discriminator_dict) +base_discriminator_from_dict = BaseDiscriminator.model_validate(base_discriminator_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/BasquePig.md b/samples/openapi3/client/petstore/python-aiohttp/docs/BasquePig.md index ee28d628722f..9844d05b3740 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/BasquePig.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/BasquePig.md @@ -16,14 +16,14 @@ from petstore_api.models.basque_pig import BasquePig # TODO update the JSON string below json = "{}" # create an instance of BasquePig from a JSON string -basque_pig_instance = BasquePig.from_json(json) +basque_pig_instance = BasquePig.model_validate_json(json) # print the JSON string representation of the object -print(BasquePig.to_json()) +print(basque_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -basque_pig_dict = basque_pig_instance.to_dict() +basque_pig_dict = basque_pig_instance.model_dump(by_alias=True) # create an instance of BasquePig from a dict -basque_pig_from_dict = BasquePig.from_dict(basque_pig_dict) +basque_pig_from_dict = BasquePig.model_validate(basque_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Bathing.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Bathing.md index 6ad70e2f67cc..2c8d8332629b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Bathing.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Bathing.md @@ -17,14 +17,14 @@ from petstore_api.models.bathing import Bathing # TODO update the JSON string below json = "{}" # create an instance of Bathing from a JSON string -bathing_instance = Bathing.from_json(json) +bathing_instance = Bathing.model_validate_json(json) # print the JSON string representation of the object -print(Bathing.to_json()) +print(bathing_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -bathing_dict = bathing_instance.to_dict() +bathing_dict = bathing_instance.model_dump(by_alias=True) # create an instance of Bathing from a dict -bathing_from_dict = Bathing.from_dict(bathing_dict) +bathing_from_dict = Bathing.model_validate(bathing_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Capitalization.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Capitalization.md index 6f564a8ed8c9..55fcc0c01cb2 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Capitalization.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Capitalization.md @@ -20,14 +20,14 @@ from petstore_api.models.capitalization import Capitalization # TODO update the JSON string below json = "{}" # create an instance of Capitalization from a JSON string -capitalization_instance = Capitalization.from_json(json) +capitalization_instance = Capitalization.model_validate_json(json) # print the JSON string representation of the object -print(Capitalization.to_json()) +print(capitalization_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -capitalization_dict = capitalization_instance.to_dict() +capitalization_dict = capitalization_instance.model_dump(by_alias=True) # create an instance of Capitalization from a dict -capitalization_from_dict = Capitalization.from_dict(capitalization_dict) +capitalization_from_dict = Capitalization.model_validate(capitalization_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Cat.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Cat.md index d0e39efdb33e..0845d68bd487 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Cat.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Cat.md @@ -15,14 +15,14 @@ from petstore_api.models.cat import Cat # TODO update the JSON string below json = "{}" # create an instance of Cat from a JSON string -cat_instance = Cat.from_json(json) +cat_instance = Cat.model_validate_json(json) # print the JSON string representation of the object -print(Cat.to_json()) +print(cat_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -cat_dict = cat_instance.to_dict() +cat_dict = cat_instance.model_dump(by_alias=True) # create an instance of Cat from a dict -cat_from_dict = Cat.from_dict(cat_dict) +cat_from_dict = Cat.model_validate(cat_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Category.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Category.md index dbde14b7344c..8a14791c7925 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Category.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Category.md @@ -16,14 +16,14 @@ from petstore_api.models.category import Category # TODO update the JSON string below json = "{}" # create an instance of Category from a JSON string -category_instance = Category.from_json(json) +category_instance = Category.model_validate_json(json) # print the JSON string representation of the object -print(Category.to_json()) +print(category_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -category_dict = category_instance.to_dict() +category_dict = category_instance.model_dump(by_alias=True) # create an instance of Category from a dict -category_from_dict = Category.from_dict(category_dict) +category_from_dict = Category.model_validate(category_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/CircularAllOfRef.md b/samples/openapi3/client/petstore/python-aiohttp/docs/CircularAllOfRef.md index 65b171177e58..f937a53cfe3c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/CircularAllOfRef.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/CircularAllOfRef.md @@ -16,14 +16,14 @@ from petstore_api.models.circular_all_of_ref import CircularAllOfRef # TODO update the JSON string below json = "{}" # create an instance of CircularAllOfRef from a JSON string -circular_all_of_ref_instance = CircularAllOfRef.from_json(json) +circular_all_of_ref_instance = CircularAllOfRef.model_validate_json(json) # print the JSON string representation of the object -print(CircularAllOfRef.to_json()) +print(circular_all_of_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -circular_all_of_ref_dict = circular_all_of_ref_instance.to_dict() +circular_all_of_ref_dict = circular_all_of_ref_instance.model_dump(by_alias=True) # create an instance of CircularAllOfRef from a dict -circular_all_of_ref_from_dict = CircularAllOfRef.from_dict(circular_all_of_ref_dict) +circular_all_of_ref_from_dict = CircularAllOfRef.model_validate(circular_all_of_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/CircularReferenceModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/CircularReferenceModel.md index 87216f7273ab..9a39f46e5d7d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/CircularReferenceModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/CircularReferenceModel.md @@ -16,14 +16,14 @@ from petstore_api.models.circular_reference_model import CircularReferenceModel # TODO update the JSON string below json = "{}" # create an instance of CircularReferenceModel from a JSON string -circular_reference_model_instance = CircularReferenceModel.from_json(json) +circular_reference_model_instance = CircularReferenceModel.model_validate_json(json) # print the JSON string representation of the object -print(CircularReferenceModel.to_json()) +print(circular_reference_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -circular_reference_model_dict = circular_reference_model_instance.to_dict() +circular_reference_model_dict = circular_reference_model_instance.model_dump(by_alias=True) # create an instance of CircularReferenceModel from a dict -circular_reference_model_from_dict = CircularReferenceModel.from_dict(circular_reference_model_dict) +circular_reference_model_from_dict = CircularReferenceModel.model_validate(circular_reference_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ClassModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ClassModel.md index ea76a5c157bf..50fbfefa7661 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ClassModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ClassModel.md @@ -16,14 +16,14 @@ from petstore_api.models.class_model import ClassModel # TODO update the JSON string below json = "{}" # create an instance of ClassModel from a JSON string -class_model_instance = ClassModel.from_json(json) +class_model_instance = ClassModel.model_validate_json(json) # print the JSON string representation of the object -print(ClassModel.to_json()) +print(class_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -class_model_dict = class_model_instance.to_dict() +class_model_dict = class_model_instance.model_dump(by_alias=True) # create an instance of ClassModel from a dict -class_model_from_dict = ClassModel.from_dict(class_model_dict) +class_model_from_dict = ClassModel.model_validate(class_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Client.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Client.md index 22321c189150..160a80da457f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Client.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Client.md @@ -15,14 +15,14 @@ from petstore_api.models.client import Client # TODO update the JSON string below json = "{}" # create an instance of Client from a JSON string -client_instance = Client.from_json(json) +client_instance = Client.model_validate_json(json) # print the JSON string representation of the object -print(Client.to_json()) +print(client_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -client_dict = client_instance.to_dict() +client_dict = client_instance.model_dump(by_alias=True) # create an instance of Client from a dict -client_from_dict = Client.from_dict(client_dict) +client_from_dict = Client.model_validate(client_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Color.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Color.md index 9ac3ab2e91f4..1425ff185040 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Color.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Color.md @@ -15,14 +15,14 @@ from petstore_api.models.color import Color # TODO update the JSON string below json = "{}" # create an instance of Color from a JSON string -color_instance = Color.from_json(json) +color_instance = Color.model_validate_json(json) # print the JSON string representation of the object -print(Color.to_json()) +print(color_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -color_dict = color_instance.to_dict() +color_dict = color_instance.model_dump(by_alias=True) # create an instance of Color from a dict -color_from_dict = Color.from_dict(color_dict) +color_from_dict = Color.model_validate(color_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Creature.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Creature.md index a4710214c198..eb0ba3b2f127 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Creature.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Creature.md @@ -16,14 +16,14 @@ from petstore_api.models.creature import Creature # TODO update the JSON string below json = "{}" # create an instance of Creature from a JSON string -creature_instance = Creature.from_json(json) +creature_instance = Creature.model_validate_json(json) # print the JSON string representation of the object -print(Creature.to_json()) +print(creature_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -creature_dict = creature_instance.to_dict() +creature_dict = creature_instance.model_dump(by_alias=True) # create an instance of Creature from a dict -creature_from_dict = Creature.from_dict(creature_dict) +creature_from_dict = Creature.model_validate(creature_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/CreatureInfo.md b/samples/openapi3/client/petstore/python-aiohttp/docs/CreatureInfo.md index db3b82bb9ff5..156d93939201 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/CreatureInfo.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/CreatureInfo.md @@ -15,14 +15,14 @@ from petstore_api.models.creature_info import CreatureInfo # TODO update the JSON string below json = "{}" # create an instance of CreatureInfo from a JSON string -creature_info_instance = CreatureInfo.from_json(json) +creature_info_instance = CreatureInfo.model_validate_json(json) # print the JSON string representation of the object -print(CreatureInfo.to_json()) +print(creature_info_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -creature_info_dict = creature_info_instance.to_dict() +creature_info_dict = creature_info_instance.model_dump(by_alias=True) # create an instance of CreatureInfo from a dict -creature_info_from_dict = CreatureInfo.from_dict(creature_info_dict) +creature_info_from_dict = CreatureInfo.model_validate(creature_info_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/DanishPig.md b/samples/openapi3/client/petstore/python-aiohttp/docs/DanishPig.md index 16941388832a..5eac27f79e79 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/DanishPig.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/DanishPig.md @@ -16,14 +16,14 @@ from petstore_api.models.danish_pig import DanishPig # TODO update the JSON string below json = "{}" # create an instance of DanishPig from a JSON string -danish_pig_instance = DanishPig.from_json(json) +danish_pig_instance = DanishPig.model_validate_json(json) # print the JSON string representation of the object -print(DanishPig.to_json()) +print(danish_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -danish_pig_dict = danish_pig_instance.to_dict() +danish_pig_dict = danish_pig_instance.model_dump(by_alias=True) # create an instance of DanishPig from a dict -danish_pig_from_dict = DanishPig.from_dict(danish_pig_dict) +danish_pig_from_dict = DanishPig.model_validate(danish_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/DeprecatedObject.md b/samples/openapi3/client/petstore/python-aiohttp/docs/DeprecatedObject.md index 6b362f379ba4..ff3aa9812e2d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/DeprecatedObject.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/DeprecatedObject.md @@ -15,14 +15,14 @@ from petstore_api.models.deprecated_object import DeprecatedObject # TODO update the JSON string below json = "{}" # create an instance of DeprecatedObject from a JSON string -deprecated_object_instance = DeprecatedObject.from_json(json) +deprecated_object_instance = DeprecatedObject.model_validate_json(json) # print the JSON string representation of the object -print(DeprecatedObject.to_json()) +print(deprecated_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -deprecated_object_dict = deprecated_object_instance.to_dict() +deprecated_object_dict = deprecated_object_instance.model_dump(by_alias=True) # create an instance of DeprecatedObject from a dict -deprecated_object_from_dict = DeprecatedObject.from_dict(deprecated_object_dict) +deprecated_object_from_dict = DeprecatedObject.model_validate(deprecated_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/DiscriminatorAllOfSub.md b/samples/openapi3/client/petstore/python-aiohttp/docs/DiscriminatorAllOfSub.md index f72b6e8e68ca..aa7af45b99fa 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/DiscriminatorAllOfSub.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/DiscriminatorAllOfSub.md @@ -14,14 +14,14 @@ from petstore_api.models.discriminator_all_of_sub import DiscriminatorAllOfSub # TODO update the JSON string below json = "{}" # create an instance of DiscriminatorAllOfSub from a JSON string -discriminator_all_of_sub_instance = DiscriminatorAllOfSub.from_json(json) +discriminator_all_of_sub_instance = DiscriminatorAllOfSub.model_validate_json(json) # print the JSON string representation of the object -print(DiscriminatorAllOfSub.to_json()) +print(discriminator_all_of_sub_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -discriminator_all_of_sub_dict = discriminator_all_of_sub_instance.to_dict() +discriminator_all_of_sub_dict = discriminator_all_of_sub_instance.model_dump(by_alias=True) # create an instance of DiscriminatorAllOfSub from a dict -discriminator_all_of_sub_from_dict = DiscriminatorAllOfSub.from_dict(discriminator_all_of_sub_dict) +discriminator_all_of_sub_from_dict = DiscriminatorAllOfSub.model_validate(discriminator_all_of_sub_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/DiscriminatorAllOfSuper.md b/samples/openapi3/client/petstore/python-aiohttp/docs/DiscriminatorAllOfSuper.md index 477c05bfc446..c21e5b2296ac 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/DiscriminatorAllOfSuper.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/DiscriminatorAllOfSuper.md @@ -15,14 +15,14 @@ from petstore_api.models.discriminator_all_of_super import DiscriminatorAllOfSup # TODO update the JSON string below json = "{}" # create an instance of DiscriminatorAllOfSuper from a JSON string -discriminator_all_of_super_instance = DiscriminatorAllOfSuper.from_json(json) +discriminator_all_of_super_instance = DiscriminatorAllOfSuper.model_validate_json(json) # print the JSON string representation of the object -print(DiscriminatorAllOfSuper.to_json()) +print(discriminator_all_of_super_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -discriminator_all_of_super_dict = discriminator_all_of_super_instance.to_dict() +discriminator_all_of_super_dict = discriminator_all_of_super_instance.model_dump(by_alias=True) # create an instance of DiscriminatorAllOfSuper from a dict -discriminator_all_of_super_from_dict = DiscriminatorAllOfSuper.from_dict(discriminator_all_of_super_dict) +discriminator_all_of_super_from_dict = DiscriminatorAllOfSuper.model_validate(discriminator_all_of_super_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Dog.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Dog.md index ed23f613d01d..2065d42f5f6b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Dog.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Dog.md @@ -15,14 +15,14 @@ from petstore_api.models.dog import Dog # TODO update the JSON string below json = "{}" # create an instance of Dog from a JSON string -dog_instance = Dog.from_json(json) +dog_instance = Dog.model_validate_json(json) # print the JSON string representation of the object -print(Dog.to_json()) +print(dog_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -dog_dict = dog_instance.to_dict() +dog_dict = dog_instance.model_dump(by_alias=True) # create an instance of Dog from a dict -dog_from_dict = Dog.from_dict(dog_dict) +dog_from_dict = Dog.model_validate(dog_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/DummyModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/DummyModel.md index 01b675977f58..dfe28d9f75b1 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/DummyModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/DummyModel.md @@ -16,14 +16,14 @@ from petstore_api.models.dummy_model import DummyModel # TODO update the JSON string below json = "{}" # create an instance of DummyModel from a JSON string -dummy_model_instance = DummyModel.from_json(json) +dummy_model_instance = DummyModel.model_validate_json(json) # print the JSON string representation of the object -print(DummyModel.to_json()) +print(dummy_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -dummy_model_dict = dummy_model_instance.to_dict() +dummy_model_dict = dummy_model_instance.model_dump(by_alias=True) # create an instance of DummyModel from a dict -dummy_model_from_dict = DummyModel.from_dict(dummy_model_dict) +dummy_model_from_dict = DummyModel.model_validate(dummy_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumArrays.md b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumArrays.md index f44617497bce..bf8b1a6cd05c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumArrays.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumArrays.md @@ -16,14 +16,14 @@ from petstore_api.models.enum_arrays import EnumArrays # TODO update the JSON string below json = "{}" # create an instance of EnumArrays from a JSON string -enum_arrays_instance = EnumArrays.from_json(json) +enum_arrays_instance = EnumArrays.model_validate_json(json) # print the JSON string representation of the object -print(EnumArrays.to_json()) +print(enum_arrays_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_arrays_dict = enum_arrays_instance.to_dict() +enum_arrays_dict = enum_arrays_instance.model_dump(by_alias=True) # create an instance of EnumArrays from a dict -enum_arrays_from_dict = EnumArrays.from_dict(enum_arrays_dict) +enum_arrays_from_dict = EnumArrays.model_validate(enum_arrays_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumRefWithDefaultValue.md b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumRefWithDefaultValue.md index eeb0dc66969f..cbe6845479eb 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumRefWithDefaultValue.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumRefWithDefaultValue.md @@ -15,14 +15,14 @@ from petstore_api.models.enum_ref_with_default_value import EnumRefWithDefaultVa # TODO update the JSON string below json = "{}" # create an instance of EnumRefWithDefaultValue from a JSON string -enum_ref_with_default_value_instance = EnumRefWithDefaultValue.from_json(json) +enum_ref_with_default_value_instance = EnumRefWithDefaultValue.model_validate_json(json) # print the JSON string representation of the object -print(EnumRefWithDefaultValue.to_json()) +print(enum_ref_with_default_value_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_ref_with_default_value_dict = enum_ref_with_default_value_instance.to_dict() +enum_ref_with_default_value_dict = enum_ref_with_default_value_instance.model_dump(by_alias=True) # create an instance of EnumRefWithDefaultValue from a dict -enum_ref_with_default_value_from_dict = EnumRefWithDefaultValue.from_dict(enum_ref_with_default_value_dict) +enum_ref_with_default_value_from_dict = EnumRefWithDefaultValue.model_validate(enum_ref_with_default_value_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumTest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumTest.md index 9f96c605d888..6ce4891aa9d5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumTest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumTest.md @@ -27,14 +27,14 @@ from petstore_api.models.enum_test import EnumTest # TODO update the JSON string below json = "{}" # create an instance of EnumTest from a JSON string -enum_test_instance = EnumTest.from_json(json) +enum_test_instance = EnumTest.model_validate_json(json) # print the JSON string representation of the object -print(EnumTest.to_json()) +print(enum_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_test_dict = enum_test_instance.to_dict() +enum_test_dict = enum_test_instance.model_dump(by_alias=True) # create an instance of EnumTest from a dict -enum_test_from_dict = EnumTest.from_dict(enum_test_dict) +enum_test_from_dict = EnumTest.model_validate(enum_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Feeding.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Feeding.md index 9f92b5d964d3..773d1373cca0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Feeding.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Feeding.md @@ -17,14 +17,14 @@ from petstore_api.models.feeding import Feeding # TODO update the JSON string below json = "{}" # create an instance of Feeding from a JSON string -feeding_instance = Feeding.from_json(json) +feeding_instance = Feeding.model_validate_json(json) # print the JSON string representation of the object -print(Feeding.to_json()) +print(feeding_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -feeding_dict = feeding_instance.to_dict() +feeding_dict = feeding_instance.model_dump(by_alias=True) # create an instance of Feeding from a dict -feeding_from_dict = Feeding.from_dict(feeding_dict) +feeding_from_dict = Feeding.model_validate(feeding_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/File.md b/samples/openapi3/client/petstore/python-aiohttp/docs/File.md index 23f0567411ce..3fe748f4f30f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/File.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/File.md @@ -16,14 +16,14 @@ from petstore_api.models.file import File # TODO update the JSON string below json = "{}" # create an instance of File from a JSON string -file_instance = File.from_json(json) +file_instance = File.model_validate_json(json) # print the JSON string representation of the object -print(File.to_json()) +print(file_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -file_dict = file_instance.to_dict() +file_dict = file_instance.model_dump(by_alias=True) # create an instance of File from a dict -file_from_dict = File.from_dict(file_dict) +file_from_dict = File.model_validate(file_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FileSchemaTestClass.md index e1118042a8ec..78bc4ae135da 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FileSchemaTestClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FileSchemaTestClass.md @@ -16,14 +16,14 @@ from petstore_api.models.file_schema_test_class import FileSchemaTestClass # TODO update the JSON string below json = "{}" # create an instance of FileSchemaTestClass from a JSON string -file_schema_test_class_instance = FileSchemaTestClass.from_json(json) +file_schema_test_class_instance = FileSchemaTestClass.model_validate_json(json) # print the JSON string representation of the object -print(FileSchemaTestClass.to_json()) +print(file_schema_test_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -file_schema_test_class_dict = file_schema_test_class_instance.to_dict() +file_schema_test_class_dict = file_schema_test_class_instance.model_dump(by_alias=True) # create an instance of FileSchemaTestClass from a dict -file_schema_test_class_from_dict = FileSchemaTestClass.from_dict(file_schema_test_class_dict) +file_schema_test_class_from_dict = FileSchemaTestClass.model_validate(file_schema_test_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FirstRef.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FirstRef.md index 94b8ddc5ac22..6da6650e5df7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FirstRef.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FirstRef.md @@ -16,14 +16,14 @@ from petstore_api.models.first_ref import FirstRef # TODO update the JSON string below json = "{}" # create an instance of FirstRef from a JSON string -first_ref_instance = FirstRef.from_json(json) +first_ref_instance = FirstRef.model_validate_json(json) # print the JSON string representation of the object -print(FirstRef.to_json()) +print(first_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -first_ref_dict = first_ref_instance.to_dict() +first_ref_dict = first_ref_instance.model_dump(by_alias=True) # create an instance of FirstRef from a dict -first_ref_from_dict = FirstRef.from_dict(first_ref_dict) +first_ref_from_dict = FirstRef.model_validate(first_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Foo.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Foo.md index f635b0daa6db..c11ae111ee22 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Foo.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Foo.md @@ -15,14 +15,14 @@ from petstore_api.models.foo import Foo # TODO update the JSON string below json = "{}" # create an instance of Foo from a JSON string -foo_instance = Foo.from_json(json) +foo_instance = Foo.model_validate_json(json) # print the JSON string representation of the object -print(Foo.to_json()) +print(foo_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -foo_dict = foo_instance.to_dict() +foo_dict = foo_instance.model_dump(by_alias=True) # create an instance of Foo from a dict -foo_from_dict = Foo.from_dict(foo_dict) +foo_from_dict = Foo.model_validate(foo_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FooGetDefaultResponse.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FooGetDefaultResponse.md index 8d84f795b00a..aaccf08bfd2e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FooGetDefaultResponse.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FooGetDefaultResponse.md @@ -15,14 +15,14 @@ from petstore_api.models.foo_get_default_response import FooGetDefaultResponse # TODO update the JSON string below json = "{}" # create an instance of FooGetDefaultResponse from a JSON string -foo_get_default_response_instance = FooGetDefaultResponse.from_json(json) +foo_get_default_response_instance = FooGetDefaultResponse.model_validate_json(json) # print the JSON string representation of the object -print(FooGetDefaultResponse.to_json()) +print(foo_get_default_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -foo_get_default_response_dict = foo_get_default_response_instance.to_dict() +foo_get_default_response_dict = foo_get_default_response_instance.model_dump(by_alias=True) # create an instance of FooGetDefaultResponse from a dict -foo_get_default_response_from_dict = FooGetDefaultResponse.from_dict(foo_get_default_response_dict) +foo_get_default_response_from_dict = FooGetDefaultResponse.model_validate(foo_get_default_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FormatTest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FormatTest.md index 714d2401bbae..98c3dc89570d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FormatTest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FormatTest.md @@ -31,14 +31,14 @@ from petstore_api.models.format_test import FormatTest # TODO update the JSON string below json = "{}" # create an instance of FormatTest from a JSON string -format_test_instance = FormatTest.from_json(json) +format_test_instance = FormatTest.model_validate_json(json) # print the JSON string representation of the object -print(FormatTest.to_json()) +print(format_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -format_test_dict = format_test_instance.to_dict() +format_test_dict = format_test_instance.model_dump(by_alias=True) # create an instance of FormatTest from a dict -format_test_from_dict = FormatTest.from_dict(format_test_dict) +format_test_from_dict = FormatTest.model_validate(format_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/HasOnlyReadOnly.md index fdc48781b15a..66dca11251aa 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/HasOnlyReadOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/HasOnlyReadOnly.md @@ -16,14 +16,14 @@ from petstore_api.models.has_only_read_only import HasOnlyReadOnly # TODO update the JSON string below json = "{}" # create an instance of HasOnlyReadOnly from a JSON string -has_only_read_only_instance = HasOnlyReadOnly.from_json(json) +has_only_read_only_instance = HasOnlyReadOnly.model_validate_json(json) # print the JSON string representation of the object -print(HasOnlyReadOnly.to_json()) +print(has_only_read_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -has_only_read_only_dict = has_only_read_only_instance.to_dict() +has_only_read_only_dict = has_only_read_only_instance.model_dump(by_alias=True) # create an instance of HasOnlyReadOnly from a dict -has_only_read_only_from_dict = HasOnlyReadOnly.from_dict(has_only_read_only_dict) +has_only_read_only_from_dict = HasOnlyReadOnly.model_validate(has_only_read_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python-aiohttp/docs/HealthCheckResult.md index d4a2b187167f..522156ae5b16 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/HealthCheckResult.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/HealthCheckResult.md @@ -16,14 +16,14 @@ from petstore_api.models.health_check_result import HealthCheckResult # TODO update the JSON string below json = "{}" # create an instance of HealthCheckResult from a JSON string -health_check_result_instance = HealthCheckResult.from_json(json) +health_check_result_instance = HealthCheckResult.model_validate_json(json) # print the JSON string representation of the object -print(HealthCheckResult.to_json()) +print(health_check_result_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -health_check_result_dict = health_check_result_instance.to_dict() +health_check_result_dict = health_check_result_instance.model_dump(by_alias=True) # create an instance of HealthCheckResult from a dict -health_check_result_from_dict = HealthCheckResult.from_dict(health_check_result_dict) +health_check_result_from_dict = HealthCheckResult.model_validate(health_check_result_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/HuntingDog.md b/samples/openapi3/client/petstore/python-aiohttp/docs/HuntingDog.md index 6db6745dd022..114dfc8575d9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/HuntingDog.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/HuntingDog.md @@ -15,14 +15,14 @@ from petstore_api.models.hunting_dog import HuntingDog # TODO update the JSON string below json = "{}" # create an instance of HuntingDog from a JSON string -hunting_dog_instance = HuntingDog.from_json(json) +hunting_dog_instance = HuntingDog.model_validate_json(json) # print the JSON string representation of the object -print(HuntingDog.to_json()) +print(hunting_dog_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -hunting_dog_dict = hunting_dog_instance.to_dict() +hunting_dog_dict = hunting_dog_instance.model_dump(by_alias=True) # create an instance of HuntingDog from a dict -hunting_dog_from_dict = HuntingDog.from_dict(hunting_dog_dict) +hunting_dog_from_dict = HuntingDog.model_validate(hunting_dog_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Info.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Info.md index db88778a9143..160c3633247c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Info.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Info.md @@ -15,14 +15,14 @@ from petstore_api.models.info import Info # TODO update the JSON string below json = "{}" # create an instance of Info from a JSON string -info_instance = Info.from_json(json) +info_instance = Info.model_validate_json(json) # print the JSON string representation of the object -print(Info.to_json()) +print(info_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -info_dict = info_instance.to_dict() +info_dict = info_instance.model_dump(by_alias=True) # create an instance of Info from a dict -info_from_dict = Info.from_dict(info_dict) +info_from_dict = Info.model_validate(info_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/InnerDictWithProperty.md b/samples/openapi3/client/petstore/python-aiohttp/docs/InnerDictWithProperty.md index 7b82ebb770b8..79234d754027 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/InnerDictWithProperty.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/InnerDictWithProperty.md @@ -15,14 +15,14 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty # TODO update the JSON string below json = "{}" # create an instance of InnerDictWithProperty from a JSON string -inner_dict_with_property_instance = InnerDictWithProperty.from_json(json) +inner_dict_with_property_instance = InnerDictWithProperty.model_validate_json(json) # print the JSON string representation of the object -print(InnerDictWithProperty.to_json()) +print(inner_dict_with_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -inner_dict_with_property_dict = inner_dict_with_property_instance.to_dict() +inner_dict_with_property_dict = inner_dict_with_property_instance.model_dump(by_alias=True) # create an instance of InnerDictWithProperty from a dict -inner_dict_with_property_from_dict = InnerDictWithProperty.from_dict(inner_dict_with_property_dict) +inner_dict_with_property_from_dict = InnerDictWithProperty.model_validate(inner_dict_with_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/InputAllOf.md b/samples/openapi3/client/petstore/python-aiohttp/docs/InputAllOf.md index 45298f5308fc..32d4100ac9de 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/InputAllOf.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/InputAllOf.md @@ -15,14 +15,14 @@ from petstore_api.models.input_all_of import InputAllOf # TODO update the JSON string below json = "{}" # create an instance of InputAllOf from a JSON string -input_all_of_instance = InputAllOf.from_json(json) +input_all_of_instance = InputAllOf.model_validate_json(json) # print the JSON string representation of the object -print(InputAllOf.to_json()) +print(input_all_of_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -input_all_of_dict = input_all_of_instance.to_dict() +input_all_of_dict = input_all_of_instance.model_dump(by_alias=True) # create an instance of InputAllOf from a dict -input_all_of_from_dict = InputAllOf.from_dict(input_all_of_dict) +input_all_of_from_dict = InputAllOf.model_validate(input_all_of_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/IntOrString.md b/samples/openapi3/client/petstore/python-aiohttp/docs/IntOrString.md index b4070b9a8c79..ea8e06339493 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/IntOrString.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/IntOrString.md @@ -14,14 +14,14 @@ from petstore_api.models.int_or_string import IntOrString # TODO update the JSON string below json = "{}" # create an instance of IntOrString from a JSON string -int_or_string_instance = IntOrString.from_json(json) +int_or_string_instance = IntOrString.model_validate_json(json) # print the JSON string representation of the object -print(IntOrString.to_json()) +print(int_or_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -int_or_string_dict = int_or_string_instance.to_dict() +int_or_string_dict = int_or_string_instance.model_dump(by_alias=True) # create an instance of IntOrString from a dict -int_or_string_from_dict = IntOrString.from_dict(int_or_string_dict) +int_or_string_from_dict = IntOrString.model_validate(int_or_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ListClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ListClass.md index 01068b7d22c3..8bc905105efe 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ListClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ListClass.md @@ -15,14 +15,14 @@ from petstore_api.models.list_class import ListClass # TODO update the JSON string below json = "{}" # create an instance of ListClass from a JSON string -list_class_instance = ListClass.from_json(json) +list_class_instance = ListClass.model_validate_json(json) # print the JSON string representation of the object -print(ListClass.to_json()) +print(list_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -list_class_dict = list_class_instance.to_dict() +list_class_dict = list_class_instance.model_dump(by_alias=True) # create an instance of ListClass from a dict -list_class_from_dict = ListClass.from_dict(list_class_dict) +list_class_from_dict = ListClass.model_validate(list_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/MapOfArrayOfModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/MapOfArrayOfModel.md index 71a4ef66b682..acea13d9a9f5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/MapOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/MapOfArrayOfModel.md @@ -15,14 +15,14 @@ from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel # TODO update the JSON string below json = "{}" # create an instance of MapOfArrayOfModel from a JSON string -map_of_array_of_model_instance = MapOfArrayOfModel.from_json(json) +map_of_array_of_model_instance = MapOfArrayOfModel.model_validate_json(json) # print the JSON string representation of the object -print(MapOfArrayOfModel.to_json()) +print(map_of_array_of_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -map_of_array_of_model_dict = map_of_array_of_model_instance.to_dict() +map_of_array_of_model_dict = map_of_array_of_model_instance.model_dump(by_alias=True) # create an instance of MapOfArrayOfModel from a dict -map_of_array_of_model_from_dict = MapOfArrayOfModel.from_dict(map_of_array_of_model_dict) +map_of_array_of_model_from_dict = MapOfArrayOfModel.model_validate(map_of_array_of_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/MapTest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/MapTest.md index d04b82e9378c..fa4501d24286 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/MapTest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/MapTest.md @@ -18,14 +18,14 @@ from petstore_api.models.map_test import MapTest # TODO update the JSON string below json = "{}" # create an instance of MapTest from a JSON string -map_test_instance = MapTest.from_json(json) +map_test_instance = MapTest.model_validate_json(json) # print the JSON string representation of the object -print(MapTest.to_json()) +print(map_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -map_test_dict = map_test_instance.to_dict() +map_test_dict = map_test_instance.model_dump(by_alias=True) # create an instance of MapTest from a dict -map_test_from_dict = MapTest.from_dict(map_test_dict) +map_test_from_dict = MapTest.model_validate(map_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md index 84134317aefc..fb354956720a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -17,14 +17,14 @@ from petstore_api.models.mixed_properties_and_additional_properties_class import # TODO update the JSON string below json = "{}" # create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string -mixed_properties_and_additional_properties_class_instance = MixedPropertiesAndAdditionalPropertiesClass.from_json(json) +mixed_properties_and_additional_properties_class_instance = MixedPropertiesAndAdditionalPropertiesClass.model_validate_json(json) # print the JSON string representation of the object -print(MixedPropertiesAndAdditionalPropertiesClass.to_json()) +print(mixed_properties_and_additional_properties_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -mixed_properties_and_additional_properties_class_dict = mixed_properties_and_additional_properties_class_instance.to_dict() +mixed_properties_and_additional_properties_class_dict = mixed_properties_and_additional_properties_class_instance.model_dump(by_alias=True) # create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict -mixed_properties_and_additional_properties_class_from_dict = MixedPropertiesAndAdditionalPropertiesClass.from_dict(mixed_properties_and_additional_properties_class_dict) +mixed_properties_and_additional_properties_class_from_dict = MixedPropertiesAndAdditionalPropertiesClass.model_validate(mixed_properties_and_additional_properties_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Model200Response.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Model200Response.md index 7fdbdefc6cec..6cffad7a6d3a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Model200Response.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Model200Response.md @@ -17,14 +17,14 @@ from petstore_api.models.model200_response import Model200Response # TODO update the JSON string below json = "{}" # create an instance of Model200Response from a JSON string -model200_response_instance = Model200Response.from_json(json) +model200_response_instance = Model200Response.model_validate_json(json) # print the JSON string representation of the object -print(Model200Response.to_json()) +print(model200_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model200_response_dict = model200_response_instance.to_dict() +model200_response_dict = model200_response_instance.model_dump(by_alias=True) # create an instance of Model200Response from a dict -model200_response_from_dict = Model200Response.from_dict(model200_response_dict) +model200_response_from_dict = Model200Response.model_validate(model200_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ModelApiResponse.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelApiResponse.md index 5ddc0db2a0f3..4fdaa910bce4 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ModelApiResponse.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelApiResponse.md @@ -17,14 +17,14 @@ from petstore_api.models.model_api_response import ModelApiResponse # TODO update the JSON string below json = "{}" # create an instance of ModelApiResponse from a JSON string -model_api_response_instance = ModelApiResponse.from_json(json) +model_api_response_instance = ModelApiResponse.model_validate_json(json) # print the JSON string representation of the object -print(ModelApiResponse.to_json()) +print(model_api_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_api_response_dict = model_api_response_instance.to_dict() +model_api_response_dict = model_api_response_instance.model_dump(by_alias=True) # create an instance of ModelApiResponse from a dict -model_api_response_from_dict = ModelApiResponse.from_dict(model_api_response_dict) +model_api_response_from_dict = ModelApiResponse.model_validate(model_api_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ModelField.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelField.md index 9073b5dbdb00..43f064bd85a4 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ModelField.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelField.md @@ -15,14 +15,14 @@ from petstore_api.models.model_field import ModelField # TODO update the JSON string below json = "{}" # create an instance of ModelField from a JSON string -model_field_instance = ModelField.from_json(json) +model_field_instance = ModelField.model_validate_json(json) # print the JSON string representation of the object -print(ModelField.to_json()) +print(model_field_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_field_dict = model_field_instance.to_dict() +model_field_dict = model_field_instance.model_dump(by_alias=True) # create an instance of ModelField from a dict -model_field_from_dict = ModelField.from_dict(model_field_dict) +model_field_from_dict = ModelField.model_validate(model_field_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ModelReturn.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelReturn.md index 7d327053b0c3..236b2bb971ee 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ModelReturn.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelReturn.md @@ -16,14 +16,14 @@ from petstore_api.models.model_return import ModelReturn # TODO update the JSON string below json = "{}" # create an instance of ModelReturn from a JSON string -model_return_instance = ModelReturn.from_json(json) +model_return_instance = ModelReturn.model_validate_json(json) # print the JSON string representation of the object -print(ModelReturn.to_json()) +print(model_return_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_return_dict = model_return_instance.to_dict() +model_return_dict = model_return_instance.model_dump(by_alias=True) # create an instance of ModelReturn from a dict -model_return_from_dict = ModelReturn.from_dict(model_return_dict) +model_return_from_dict = ModelReturn.model_validate(model_return_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/MultiArrays.md b/samples/openapi3/client/petstore/python-aiohttp/docs/MultiArrays.md index fea5139e7e73..9cf5c5bb1faa 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/MultiArrays.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/MultiArrays.md @@ -16,14 +16,14 @@ from petstore_api.models.multi_arrays import MultiArrays # TODO update the JSON string below json = "{}" # create an instance of MultiArrays from a JSON string -multi_arrays_instance = MultiArrays.from_json(json) +multi_arrays_instance = MultiArrays.model_validate_json(json) # print the JSON string representation of the object -print(MultiArrays.to_json()) +print(multi_arrays_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -multi_arrays_dict = multi_arrays_instance.to_dict() +multi_arrays_dict = multi_arrays_instance.model_dump(by_alias=True) # create an instance of MultiArrays from a dict -multi_arrays_from_dict = MultiArrays.from_dict(multi_arrays_dict) +multi_arrays_from_dict = MultiArrays.model_validate(multi_arrays_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Name.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Name.md index 5a04ec1ada06..f9d2da4cccd2 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Name.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Name.md @@ -19,14 +19,14 @@ from petstore_api.models.name import Name # TODO update the JSON string below json = "{}" # create an instance of Name from a JSON string -name_instance = Name.from_json(json) +name_instance = Name.model_validate_json(json) # print the JSON string representation of the object -print(Name.to_json()) +print(name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -name_dict = name_instance.to_dict() +name_dict = name_instance.model_dump(by_alias=True) # create an instance of Name from a dict -name_from_dict = Name.from_dict(name_dict) +name_from_dict = Name.model_validate(name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/NullableClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/NullableClass.md index 0387dcc2c67a..cd84aa96eb19 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/NullableClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/NullableClass.md @@ -27,14 +27,14 @@ from petstore_api.models.nullable_class import NullableClass # TODO update the JSON string below json = "{}" # create an instance of NullableClass from a JSON string -nullable_class_instance = NullableClass.from_json(json) +nullable_class_instance = NullableClass.model_validate_json(json) # print the JSON string representation of the object -print(NullableClass.to_json()) +print(nullable_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -nullable_class_dict = nullable_class_instance.to_dict() +nullable_class_dict = nullable_class_instance.model_dump(by_alias=True) # create an instance of NullableClass from a dict -nullable_class_from_dict = NullableClass.from_dict(nullable_class_dict) +nullable_class_from_dict = NullableClass.model_validate(nullable_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/NullableProperty.md b/samples/openapi3/client/petstore/python-aiohttp/docs/NullableProperty.md index 30edaf4844b2..c0ef9b80fcb5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/NullableProperty.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/NullableProperty.md @@ -16,14 +16,14 @@ from petstore_api.models.nullable_property import NullableProperty # TODO update the JSON string below json = "{}" # create an instance of NullableProperty from a JSON string -nullable_property_instance = NullableProperty.from_json(json) +nullable_property_instance = NullableProperty.model_validate_json(json) # print the JSON string representation of the object -print(NullableProperty.to_json()) +print(nullable_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -nullable_property_dict = nullable_property_instance.to_dict() +nullable_property_dict = nullable_property_instance.model_dump(by_alias=True) # create an instance of NullableProperty from a dict -nullable_property_from_dict = NullableProperty.from_dict(nullable_property_dict) +nullable_property_from_dict = NullableProperty.model_validate(nullable_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/NumberOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/NumberOnly.md index 415dd25585d4..f1caf70ea2b7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/NumberOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/NumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.number_only import NumberOnly # TODO update the JSON string below json = "{}" # create an instance of NumberOnly from a JSON string -number_only_instance = NumberOnly.from_json(json) +number_only_instance = NumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(NumberOnly.to_json()) +print(number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -number_only_dict = number_only_instance.to_dict() +number_only_dict = number_only_instance.model_dump(by_alias=True) # create an instance of NumberOnly from a dict -number_only_from_dict = NumberOnly.from_dict(number_only_dict) +number_only_from_dict = NumberOnly.model_validate(number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectToTestAdditionalProperties.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectToTestAdditionalProperties.md index f6bc34c98e65..f201a9627dc3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectToTestAdditionalProperties.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectToTestAdditionalProperties.md @@ -16,14 +16,14 @@ from petstore_api.models.object_to_test_additional_properties import ObjectToTes # TODO update the JSON string below json = "{}" # create an instance of ObjectToTestAdditionalProperties from a JSON string -object_to_test_additional_properties_instance = ObjectToTestAdditionalProperties.from_json(json) +object_to_test_additional_properties_instance = ObjectToTestAdditionalProperties.model_validate_json(json) # print the JSON string representation of the object -print(ObjectToTestAdditionalProperties.to_json()) +print(object_to_test_additional_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -object_to_test_additional_properties_dict = object_to_test_additional_properties_instance.to_dict() +object_to_test_additional_properties_dict = object_to_test_additional_properties_instance.model_dump(by_alias=True) # create an instance of ObjectToTestAdditionalProperties from a dict -object_to_test_additional_properties_from_dict = ObjectToTestAdditionalProperties.from_dict(object_to_test_additional_properties_dict) +object_to_test_additional_properties_from_dict = ObjectToTestAdditionalProperties.model_validate(object_to_test_additional_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectWithDeprecatedFields.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectWithDeprecatedFields.md index 6dbd2ace04f1..86cce93ba775 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectWithDeprecatedFields.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectWithDeprecatedFields.md @@ -18,14 +18,14 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecat # TODO update the JSON string below json = "{}" # create an instance of ObjectWithDeprecatedFields from a JSON string -object_with_deprecated_fields_instance = ObjectWithDeprecatedFields.from_json(json) +object_with_deprecated_fields_instance = ObjectWithDeprecatedFields.model_validate_json(json) # print the JSON string representation of the object -print(ObjectWithDeprecatedFields.to_json()) +print(object_with_deprecated_fields_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -object_with_deprecated_fields_dict = object_with_deprecated_fields_instance.to_dict() +object_with_deprecated_fields_dict = object_with_deprecated_fields_instance.model_dump(by_alias=True) # create an instance of ObjectWithDeprecatedFields from a dict -object_with_deprecated_fields_from_dict = ObjectWithDeprecatedFields.from_dict(object_with_deprecated_fields_dict) +object_with_deprecated_fields_from_dict = ObjectWithDeprecatedFields.model_validate(object_with_deprecated_fields_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Order.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Order.md index 00526b8d04b9..f5410bc8d0f3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Order.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Order.md @@ -20,14 +20,14 @@ from petstore_api.models.order import Order # TODO update the JSON string below json = "{}" # create an instance of Order from a JSON string -order_instance = Order.from_json(json) +order_instance = Order.model_validate_json(json) # print the JSON string representation of the object -print(Order.to_json()) +print(order_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -order_dict = order_instance.to_dict() +order_dict = order_instance.model_dump(by_alias=True) # create an instance of Order from a dict -order_from_dict = Order.from_dict(order_dict) +order_from_dict = Order.model_validate(order_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterComposite.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterComposite.md index c8242c2d2653..9df82e2abc87 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterComposite.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterComposite.md @@ -17,14 +17,14 @@ from petstore_api.models.outer_composite import OuterComposite # TODO update the JSON string below json = "{}" # create an instance of OuterComposite from a JSON string -outer_composite_instance = OuterComposite.from_json(json) +outer_composite_instance = OuterComposite.model_validate_json(json) # print the JSON string representation of the object -print(OuterComposite.to_json()) +print(outer_composite_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -outer_composite_dict = outer_composite_instance.to_dict() +outer_composite_dict = outer_composite_instance.model_dump(by_alias=True) # create an instance of OuterComposite from a dict -outer_composite_from_dict = OuterComposite.from_dict(outer_composite_dict) +outer_composite_from_dict = OuterComposite.model_validate(outer_composite_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterObjectWithEnumProperty.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterObjectWithEnumProperty.md index 6137dbd98da6..d23ccc3757bb 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterObjectWithEnumProperty.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterObjectWithEnumProperty.md @@ -16,14 +16,14 @@ from petstore_api.models.outer_object_with_enum_property import OuterObjectWithE # TODO update the JSON string below json = "{}" # create an instance of OuterObjectWithEnumProperty from a JSON string -outer_object_with_enum_property_instance = OuterObjectWithEnumProperty.from_json(json) +outer_object_with_enum_property_instance = OuterObjectWithEnumProperty.model_validate_json(json) # print the JSON string representation of the object -print(OuterObjectWithEnumProperty.to_json()) +print(outer_object_with_enum_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -outer_object_with_enum_property_dict = outer_object_with_enum_property_instance.to_dict() +outer_object_with_enum_property_dict = outer_object_with_enum_property_instance.model_dump(by_alias=True) # create an instance of OuterObjectWithEnumProperty from a dict -outer_object_with_enum_property_from_dict = OuterObjectWithEnumProperty.from_dict(outer_object_with_enum_property_dict) +outer_object_with_enum_property_from_dict = OuterObjectWithEnumProperty.model_validate(outer_object_with_enum_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Parent.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Parent.md index 7387f9250aad..21df089ea756 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Parent.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Parent.md @@ -15,14 +15,14 @@ from petstore_api.models.parent import Parent # TODO update the JSON string below json = "{}" # create an instance of Parent from a JSON string -parent_instance = Parent.from_json(json) +parent_instance = Parent.model_validate_json(json) # print the JSON string representation of the object -print(Parent.to_json()) +print(parent_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -parent_dict = parent_instance.to_dict() +parent_dict = parent_instance.model_dump(by_alias=True) # create an instance of Parent from a dict -parent_from_dict = Parent.from_dict(parent_dict) +parent_from_dict = Parent.model_validate(parent_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ParentWithOptionalDict.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ParentWithOptionalDict.md index bfc8688ea26f..a6ee19fd1a74 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ParentWithOptionalDict.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ParentWithOptionalDict.md @@ -15,14 +15,14 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict # TODO update the JSON string below json = "{}" # create an instance of ParentWithOptionalDict from a JSON string -parent_with_optional_dict_instance = ParentWithOptionalDict.from_json(json) +parent_with_optional_dict_instance = ParentWithOptionalDict.model_validate_json(json) # print the JSON string representation of the object -print(ParentWithOptionalDict.to_json()) +print(parent_with_optional_dict_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -parent_with_optional_dict_dict = parent_with_optional_dict_instance.to_dict() +parent_with_optional_dict_dict = parent_with_optional_dict_instance.model_dump(by_alias=True) # create an instance of ParentWithOptionalDict from a dict -parent_with_optional_dict_from_dict = ParentWithOptionalDict.from_dict(parent_with_optional_dict_dict) +parent_with_optional_dict_from_dict = ParentWithOptionalDict.model_validate(parent_with_optional_dict_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Pet.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Pet.md index 5329cf2fb925..179b71891d9d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Pet.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Pet.md @@ -20,14 +20,14 @@ from petstore_api.models.pet import Pet # TODO update the JSON string below json = "{}" # create an instance of Pet from a JSON string -pet_instance = Pet.from_json(json) +pet_instance = Pet.model_validate_json(json) # print the JSON string representation of the object -print(Pet.to_json()) +print(pet_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pet_dict = pet_instance.to_dict() +pet_dict = pet_instance.model_dump(by_alias=True) # create an instance of Pet from a dict -pet_from_dict = Pet.from_dict(pet_dict) +pet_from_dict = Pet.model_validate(pet_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Pig.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Pig.md index 625930676083..2e275198c547 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Pig.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Pig.md @@ -17,14 +17,14 @@ from petstore_api.models.pig import Pig # TODO update the JSON string below json = "{}" # create an instance of Pig from a JSON string -pig_instance = Pig.from_json(json) +pig_instance = Pig.model_validate_json(json) # print the JSON string representation of the object -print(Pig.to_json()) +print(pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pig_dict = pig_instance.to_dict() +pig_dict = pig_instance.model_dump(by_alias=True) # create an instance of Pig from a dict -pig_from_dict = Pig.from_dict(pig_dict) +pig_from_dict = Pig.model_validate(pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/PonySizes.md b/samples/openapi3/client/petstore/python-aiohttp/docs/PonySizes.md index ced44c872060..6bb28b418b6d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/PonySizes.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/PonySizes.md @@ -15,14 +15,14 @@ from petstore_api.models.pony_sizes import PonySizes # TODO update the JSON string below json = "{}" # create an instance of PonySizes from a JSON string -pony_sizes_instance = PonySizes.from_json(json) +pony_sizes_instance = PonySizes.model_validate_json(json) # print the JSON string representation of the object -print(PonySizes.to_json()) +print(pony_sizes_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pony_sizes_dict = pony_sizes_instance.to_dict() +pony_sizes_dict = pony_sizes_instance.model_dump(by_alias=True) # create an instance of PonySizes from a dict -pony_sizes_from_dict = PonySizes.from_dict(pony_sizes_dict) +pony_sizes_from_dict = PonySizes.model_validate(pony_sizes_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/PoopCleaning.md b/samples/openapi3/client/petstore/python-aiohttp/docs/PoopCleaning.md index 8f9c25e08316..3bf20593f929 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/PoopCleaning.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/PoopCleaning.md @@ -17,14 +17,14 @@ from petstore_api.models.poop_cleaning import PoopCleaning # TODO update the JSON string below json = "{}" # create an instance of PoopCleaning from a JSON string -poop_cleaning_instance = PoopCleaning.from_json(json) +poop_cleaning_instance = PoopCleaning.model_validate_json(json) # print the JSON string representation of the object -print(PoopCleaning.to_json()) +print(poop_cleaning_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -poop_cleaning_dict = poop_cleaning_instance.to_dict() +poop_cleaning_dict = poop_cleaning_instance.model_dump(by_alias=True) # create an instance of PoopCleaning from a dict -poop_cleaning_from_dict = PoopCleaning.from_dict(poop_cleaning_dict) +poop_cleaning_from_dict = PoopCleaning.model_validate(poop_cleaning_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/PrimitiveString.md b/samples/openapi3/client/petstore/python-aiohttp/docs/PrimitiveString.md index 85ceb632e167..a1a9a3dc81b6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/PrimitiveString.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/PrimitiveString.md @@ -15,14 +15,14 @@ from petstore_api.models.primitive_string import PrimitiveString # TODO update the JSON string below json = "{}" # create an instance of PrimitiveString from a JSON string -primitive_string_instance = PrimitiveString.from_json(json) +primitive_string_instance = PrimitiveString.model_validate_json(json) # print the JSON string representation of the object -print(PrimitiveString.to_json()) +print(primitive_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -primitive_string_dict = primitive_string_instance.to_dict() +primitive_string_dict = primitive_string_instance.model_dump(by_alias=True) # create an instance of PrimitiveString from a dict -primitive_string_from_dict = PrimitiveString.from_dict(primitive_string_dict) +primitive_string_from_dict = PrimitiveString.model_validate(primitive_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyMap.md b/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyMap.md index a55a0e5c6f01..5fcda1f7803d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyMap.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyMap.md @@ -15,14 +15,14 @@ from petstore_api.models.property_map import PropertyMap # TODO update the JSON string below json = "{}" # create an instance of PropertyMap from a JSON string -property_map_instance = PropertyMap.from_json(json) +property_map_instance = PropertyMap.model_validate_json(json) # print the JSON string representation of the object -print(PropertyMap.to_json()) +print(property_map_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -property_map_dict = property_map_instance.to_dict() +property_map_dict = property_map_instance.model_dump(by_alias=True) # create an instance of PropertyMap from a dict -property_map_from_dict = PropertyMap.from_dict(property_map_dict) +property_map_from_dict = PropertyMap.model_validate(property_map_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyNameCollision.md b/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyNameCollision.md index 40c233670dd0..a4a8405fe847 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyNameCollision.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyNameCollision.md @@ -17,14 +17,14 @@ from petstore_api.models.property_name_collision import PropertyNameCollision # TODO update the JSON string below json = "{}" # create an instance of PropertyNameCollision from a JSON string -property_name_collision_instance = PropertyNameCollision.from_json(json) +property_name_collision_instance = PropertyNameCollision.model_validate_json(json) # print the JSON string representation of the object -print(PropertyNameCollision.to_json()) +print(property_name_collision_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -property_name_collision_dict = property_name_collision_instance.to_dict() +property_name_collision_dict = property_name_collision_instance.model_dump(by_alias=True) # create an instance of PropertyNameCollision from a dict -property_name_collision_from_dict = PropertyNameCollision.from_dict(property_name_collision_dict) +property_name_collision_from_dict = PropertyNameCollision.model_validate(property_name_collision_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ReadOnlyFirst.md index 686ec5da41c9..e55fe102b673 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ReadOnlyFirst.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ReadOnlyFirst.md @@ -16,14 +16,14 @@ from petstore_api.models.read_only_first import ReadOnlyFirst # TODO update the JSON string below json = "{}" # create an instance of ReadOnlyFirst from a JSON string -read_only_first_instance = ReadOnlyFirst.from_json(json) +read_only_first_instance = ReadOnlyFirst.model_validate_json(json) # print the JSON string representation of the object -print(ReadOnlyFirst.to_json()) +print(read_only_first_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -read_only_first_dict = read_only_first_instance.to_dict() +read_only_first_dict = read_only_first_instance.model_dump(by_alias=True) # create an instance of ReadOnlyFirst from a dict -read_only_first_from_dict = ReadOnlyFirst.from_dict(read_only_first_dict) +read_only_first_from_dict = ReadOnlyFirst.model_validate(read_only_first_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SecondCircularAllOfRef.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SecondCircularAllOfRef.md index 65ebdd4c7e1d..47fb4daf97a4 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SecondCircularAllOfRef.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SecondCircularAllOfRef.md @@ -16,14 +16,14 @@ from petstore_api.models.second_circular_all_of_ref import SecondCircularAllOfRe # TODO update the JSON string below json = "{}" # create an instance of SecondCircularAllOfRef from a JSON string -second_circular_all_of_ref_instance = SecondCircularAllOfRef.from_json(json) +second_circular_all_of_ref_instance = SecondCircularAllOfRef.model_validate_json(json) # print the JSON string representation of the object -print(SecondCircularAllOfRef.to_json()) +print(second_circular_all_of_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -second_circular_all_of_ref_dict = second_circular_all_of_ref_instance.to_dict() +second_circular_all_of_ref_dict = second_circular_all_of_ref_instance.model_dump(by_alias=True) # create an instance of SecondCircularAllOfRef from a dict -second_circular_all_of_ref_from_dict = SecondCircularAllOfRef.from_dict(second_circular_all_of_ref_dict) +second_circular_all_of_ref_from_dict = SecondCircularAllOfRef.model_validate(second_circular_all_of_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SecondRef.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SecondRef.md index dfb1a0ac6db5..fa0b9f285e0c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SecondRef.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SecondRef.md @@ -16,14 +16,14 @@ from petstore_api.models.second_ref import SecondRef # TODO update the JSON string below json = "{}" # create an instance of SecondRef from a JSON string -second_ref_instance = SecondRef.from_json(json) +second_ref_instance = SecondRef.model_validate_json(json) # print the JSON string representation of the object -print(SecondRef.to_json()) +print(second_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -second_ref_dict = second_ref_instance.to_dict() +second_ref_dict = second_ref_instance.model_dump(by_alias=True) # create an instance of SecondRef from a dict -second_ref_from_dict = SecondRef.from_dict(second_ref_dict) +second_ref_from_dict = SecondRef.model_validate(second_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SelfReferenceModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SelfReferenceModel.md index 208cdac04b6f..af3c77d0524b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SelfReferenceModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SelfReferenceModel.md @@ -16,14 +16,14 @@ from petstore_api.models.self_reference_model import SelfReferenceModel # TODO update the JSON string below json = "{}" # create an instance of SelfReferenceModel from a JSON string -self_reference_model_instance = SelfReferenceModel.from_json(json) +self_reference_model_instance = SelfReferenceModel.model_validate_json(json) # print the JSON string representation of the object -print(SelfReferenceModel.to_json()) +print(self_reference_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -self_reference_model_dict = self_reference_model_instance.to_dict() +self_reference_model_dict = self_reference_model_instance.model_dump(by_alias=True) # create an instance of SelfReferenceModel from a dict -self_reference_model_from_dict = SelfReferenceModel.from_dict(self_reference_model_dict) +self_reference_model_from_dict = SelfReferenceModel.model_validate(self_reference_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialModelName.md index 35303f34efd2..589dbeb14b94 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialModelName.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialModelName.md @@ -15,14 +15,14 @@ from petstore_api.models.special_model_name import SpecialModelName # TODO update the JSON string below json = "{}" # create an instance of SpecialModelName from a JSON string -special_model_name_instance = SpecialModelName.from_json(json) +special_model_name_instance = SpecialModelName.model_validate_json(json) # print the JSON string representation of the object -print(SpecialModelName.to_json()) +print(special_model_name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -special_model_name_dict = special_model_name_instance.to_dict() +special_model_name_dict = special_model_name_instance.model_dump(by_alias=True) # create an instance of SpecialModelName from a dict -special_model_name_from_dict = SpecialModelName.from_dict(special_model_name_dict) +special_model_name_from_dict = SpecialModelName.model_validate(special_model_name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialName.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialName.md index ccc550b16e33..19da9016451c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialName.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialName.md @@ -17,14 +17,14 @@ from petstore_api.models.special_name import SpecialName # TODO update the JSON string below json = "{}" # create an instance of SpecialName from a JSON string -special_name_instance = SpecialName.from_json(json) +special_name_instance = SpecialName.model_validate_json(json) # print the JSON string representation of the object -print(SpecialName.to_json()) +print(special_name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -special_name_dict = special_name_instance.to_dict() +special_name_dict = special_name_instance.model_dump(by_alias=True) # create an instance of SpecialName from a dict -special_name_from_dict = SpecialName.from_dict(special_name_dict) +special_name_from_dict = SpecialName.model_validate(special_name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Tag.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Tag.md index 4106d9cfe5db..66339d14c875 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Tag.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Tag.md @@ -16,14 +16,14 @@ from petstore_api.models.tag import Tag # TODO update the JSON string below json = "{}" # create an instance of Tag from a JSON string -tag_instance = Tag.from_json(json) +tag_instance = Tag.model_validate_json(json) # print the JSON string representation of the object -print(Tag.to_json()) +print(tag_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tag_dict = tag_instance.to_dict() +tag_dict = tag_instance.model_dump(by_alias=True) # create an instance of Tag from a dict -tag_from_dict = Tag.from_dict(tag_dict) +tag_from_dict = Tag.model_validate(tag_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Task.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Task.md index 85fa2776a059..229ed6510a11 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Task.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Task.md @@ -17,14 +17,14 @@ from petstore_api.models.task import Task # TODO update the JSON string below json = "{}" # create an instance of Task from a JSON string -task_instance = Task.from_json(json) +task_instance = Task.model_validate_json(json) # print the JSON string representation of the object -print(Task.to_json()) +print(task_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -task_dict = task_instance.to_dict() +task_dict = task_instance.model_dump(by_alias=True) # create an instance of Task from a dict -task_from_dict = Task.from_dict(task_dict) +task_from_dict = Task.model_validate(task_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TaskActivity.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TaskActivity.md index e905a477292d..c025d32ba436 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/TaskActivity.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TaskActivity.md @@ -17,14 +17,14 @@ from petstore_api.models.task_activity import TaskActivity # TODO update the JSON string below json = "{}" # create an instance of TaskActivity from a JSON string -task_activity_instance = TaskActivity.from_json(json) +task_activity_instance = TaskActivity.model_validate_json(json) # print the JSON string representation of the object -print(TaskActivity.to_json()) +print(task_activity_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -task_activity_dict = task_activity_instance.to_dict() +task_activity_dict = task_activity_instance.model_dump(by_alias=True) # create an instance of TaskActivity from a dict -task_activity_from_dict = TaskActivity.from_dict(task_activity_dict) +task_activity_from_dict = TaskActivity.model_validate(task_activity_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel400Response.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel400Response.md index be416bbad0f7..fed06705b55b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel400Response.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel400Response.md @@ -15,14 +15,14 @@ from petstore_api.models.test_error_responses_with_model400_response import Test # TODO update the JSON string below json = "{}" # create an instance of TestErrorResponsesWithModel400Response from a JSON string -test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.from_json(json) +test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.model_validate_json(json) # print the JSON string representation of the object -print(TestErrorResponsesWithModel400Response.to_json()) +print(test_error_responses_with_model400_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.to_dict() +test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.model_dump(by_alias=True) # create an instance of TestErrorResponsesWithModel400Response from a dict -test_error_responses_with_model400_response_from_dict = TestErrorResponsesWithModel400Response.from_dict(test_error_responses_with_model400_response_dict) +test_error_responses_with_model400_response_from_dict = TestErrorResponsesWithModel400Response.model_validate(test_error_responses_with_model400_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel404Response.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel404Response.md index 1c984f847bf1..8813e0792d22 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel404Response.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel404Response.md @@ -15,14 +15,14 @@ from petstore_api.models.test_error_responses_with_model404_response import Test # TODO update the JSON string below json = "{}" # create an instance of TestErrorResponsesWithModel404Response from a JSON string -test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.from_json(json) +test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.model_validate_json(json) # print the JSON string representation of the object -print(TestErrorResponsesWithModel404Response.to_json()) +print(test_error_responses_with_model404_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.to_dict() +test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.model_dump(by_alias=True) # create an instance of TestErrorResponsesWithModel404Response from a dict -test_error_responses_with_model404_response_from_dict = TestErrorResponsesWithModel404Response.from_dict(test_error_responses_with_model404_response_dict) +test_error_responses_with_model404_response_from_dict = TestErrorResponsesWithModel404Response.model_validate(test_error_responses_with_model404_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md index 511132d689be..870cd8850e6b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -15,14 +15,14 @@ from petstore_api.models.test_inline_freeform_additional_properties_request impo # TODO update the JSON string below json = "{}" # create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string -test_inline_freeform_additional_properties_request_instance = TestInlineFreeformAdditionalPropertiesRequest.from_json(json) +test_inline_freeform_additional_properties_request_instance = TestInlineFreeformAdditionalPropertiesRequest.model_validate_json(json) # print the JSON string representation of the object -print(TestInlineFreeformAdditionalPropertiesRequest.to_json()) +print(test_inline_freeform_additional_properties_request_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_inline_freeform_additional_properties_request_dict = test_inline_freeform_additional_properties_request_instance.to_dict() +test_inline_freeform_additional_properties_request_dict = test_inline_freeform_additional_properties_request_instance.model_dump(by_alias=True) # create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict -test_inline_freeform_additional_properties_request_from_dict = TestInlineFreeformAdditionalPropertiesRequest.from_dict(test_inline_freeform_additional_properties_request_dict) +test_inline_freeform_additional_properties_request_from_dict = TestInlineFreeformAdditionalPropertiesRequest.model_validate(test_inline_freeform_additional_properties_request_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TestModelWithEnumDefault.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TestModelWithEnumDefault.md index 7d46e86deba4..1f63056fe0f1 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/TestModelWithEnumDefault.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TestModelWithEnumDefault.md @@ -19,14 +19,14 @@ from petstore_api.models.test_model_with_enum_default import TestModelWithEnumDe # TODO update the JSON string below json = "{}" # create an instance of TestModelWithEnumDefault from a JSON string -test_model_with_enum_default_instance = TestModelWithEnumDefault.from_json(json) +test_model_with_enum_default_instance = TestModelWithEnumDefault.model_validate_json(json) # print the JSON string representation of the object -print(TestModelWithEnumDefault.to_json()) +print(test_model_with_enum_default_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_model_with_enum_default_dict = test_model_with_enum_default_instance.to_dict() +test_model_with_enum_default_dict = test_model_with_enum_default_instance.model_dump(by_alias=True) # create an instance of TestModelWithEnumDefault from a dict -test_model_with_enum_default_from_dict = TestModelWithEnumDefault.from_dict(test_model_with_enum_default_dict) +test_model_with_enum_default_from_dict = TestModelWithEnumDefault.model_validate(test_model_with_enum_default_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TestObjectForMultipartRequestsRequestMarker.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TestObjectForMultipartRequestsRequestMarker.md index ff0ca9ee00ac..bb685d44835a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/TestObjectForMultipartRequestsRequestMarker.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TestObjectForMultipartRequestsRequestMarker.md @@ -15,14 +15,14 @@ from petstore_api.models.test_object_for_multipart_requests_request_marker impor # TODO update the JSON string below json = "{}" # create an instance of TestObjectForMultipartRequestsRequestMarker from a JSON string -test_object_for_multipart_requests_request_marker_instance = TestObjectForMultipartRequestsRequestMarker.from_json(json) +test_object_for_multipart_requests_request_marker_instance = TestObjectForMultipartRequestsRequestMarker.model_validate_json(json) # print the JSON string representation of the object -print(TestObjectForMultipartRequestsRequestMarker.to_json()) +print(test_object_for_multipart_requests_request_marker_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_object_for_multipart_requests_request_marker_dict = test_object_for_multipart_requests_request_marker_instance.to_dict() +test_object_for_multipart_requests_request_marker_dict = test_object_for_multipart_requests_request_marker_instance.model_dump(by_alias=True) # create an instance of TestObjectForMultipartRequestsRequestMarker from a dict -test_object_for_multipart_requests_request_marker_from_dict = TestObjectForMultipartRequestsRequestMarker.from_dict(test_object_for_multipart_requests_request_marker_dict) +test_object_for_multipart_requests_request_marker_from_dict = TestObjectForMultipartRequestsRequestMarker.model_validate(test_object_for_multipart_requests_request_marker_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Tiger.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Tiger.md index f1cf2133f0f7..90c7d8770979 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Tiger.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Tiger.md @@ -15,14 +15,14 @@ from petstore_api.models.tiger import Tiger # TODO update the JSON string below json = "{}" # create an instance of Tiger from a JSON string -tiger_instance = Tiger.from_json(json) +tiger_instance = Tiger.model_validate_json(json) # print the JSON string representation of the object -print(Tiger.to_json()) +print(tiger_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tiger_dict = tiger_instance.to_dict() +tiger_dict = tiger_instance.model_dump(by_alias=True) # create an instance of Tiger from a dict -tiger_from_dict = Tiger.from_dict(tiger_dict) +tiger_from_dict = Tiger.model_validate(tiger_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalModelListProperties.md b/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalModelListProperties.md index 68cd00ab0a7a..0b411bf5df7b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalModelListProperties.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalModelListProperties.md @@ -15,14 +15,14 @@ from petstore_api.models.unnamed_dict_with_additional_model_list_properties impo # TODO update the JSON string below json = "{}" # create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string -unnamed_dict_with_additional_model_list_properties_instance = UnnamedDictWithAdditionalModelListProperties.from_json(json) +unnamed_dict_with_additional_model_list_properties_instance = UnnamedDictWithAdditionalModelListProperties.model_validate_json(json) # print the JSON string representation of the object -print(UnnamedDictWithAdditionalModelListProperties.to_json()) +print(unnamed_dict_with_additional_model_list_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -unnamed_dict_with_additional_model_list_properties_dict = unnamed_dict_with_additional_model_list_properties_instance.to_dict() +unnamed_dict_with_additional_model_list_properties_dict = unnamed_dict_with_additional_model_list_properties_instance.model_dump(by_alias=True) # create an instance of UnnamedDictWithAdditionalModelListProperties from a dict -unnamed_dict_with_additional_model_list_properties_from_dict = UnnamedDictWithAdditionalModelListProperties.from_dict(unnamed_dict_with_additional_model_list_properties_dict) +unnamed_dict_with_additional_model_list_properties_from_dict = UnnamedDictWithAdditionalModelListProperties.model_validate(unnamed_dict_with_additional_model_list_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalStringListProperties.md b/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalStringListProperties.md index 045b0e22ad09..def639720586 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalStringListProperties.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalStringListProperties.md @@ -15,14 +15,14 @@ from petstore_api.models.unnamed_dict_with_additional_string_list_properties imp # TODO update the JSON string below json = "{}" # create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string -unnamed_dict_with_additional_string_list_properties_instance = UnnamedDictWithAdditionalStringListProperties.from_json(json) +unnamed_dict_with_additional_string_list_properties_instance = UnnamedDictWithAdditionalStringListProperties.model_validate_json(json) # print the JSON string representation of the object -print(UnnamedDictWithAdditionalStringListProperties.to_json()) +print(unnamed_dict_with_additional_string_list_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -unnamed_dict_with_additional_string_list_properties_dict = unnamed_dict_with_additional_string_list_properties_instance.to_dict() +unnamed_dict_with_additional_string_list_properties_dict = unnamed_dict_with_additional_string_list_properties_instance.model_dump(by_alias=True) # create an instance of UnnamedDictWithAdditionalStringListProperties from a dict -unnamed_dict_with_additional_string_list_properties_from_dict = UnnamedDictWithAdditionalStringListProperties.from_dict(unnamed_dict_with_additional_string_list_properties_dict) +unnamed_dict_with_additional_string_list_properties_from_dict = UnnamedDictWithAdditionalStringListProperties.model_validate(unnamed_dict_with_additional_string_list_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md index 141027780371..35be1642e660 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -16,14 +16,14 @@ from petstore_api.models.upload_file_with_additional_properties_request_object i # TODO update the JSON string below json = "{}" # create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string -upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.from_json(json) +upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.model_validate_json(json) # print the JSON string representation of the object -print(UploadFileWithAdditionalPropertiesRequestObject.to_json()) +print(upload_file_with_additional_properties_request_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.to_dict() +upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.model_dump(by_alias=True) # create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict -upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.from_dict(upload_file_with_additional_properties_request_object_dict) +upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.model_validate(upload_file_with_additional_properties_request_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/User.md b/samples/openapi3/client/petstore/python-aiohttp/docs/User.md index c45d26d27043..8f4ae3d04712 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/User.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/User.md @@ -22,14 +22,14 @@ from petstore_api.models.user import User # TODO update the JSON string below json = "{}" # create an instance of User from a JSON string -user_instance = User.from_json(json) +user_instance = User.model_validate_json(json) # print the JSON string representation of the object -print(User.to_json()) +print(user_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -user_dict = user_instance.to_dict() +user_dict = user_instance.model_dump(by_alias=True) # create an instance of User from a dict -user_from_dict = User.from_dict(user_dict) +user_from_dict = User.model_validate(user_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/WithNestedOneOf.md b/samples/openapi3/client/petstore/python-aiohttp/docs/WithNestedOneOf.md index e7bbbc28fc2d..12d648bb920d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/WithNestedOneOf.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/WithNestedOneOf.md @@ -17,14 +17,14 @@ from petstore_api.models.with_nested_one_of import WithNestedOneOf # TODO update the JSON string below json = "{}" # create an instance of WithNestedOneOf from a JSON string -with_nested_one_of_instance = WithNestedOneOf.from_json(json) +with_nested_one_of_instance = WithNestedOneOf.model_validate_json(json) # print the JSON string representation of the object -print(WithNestedOneOf.to_json()) +print(with_nested_one_of_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -with_nested_one_of_dict = with_nested_one_of_instance.to_dict() +with_nested_one_of_dict = with_nested_one_of_instance.model_dump(by_alias=True) # create an instance of WithNestedOneOf from a dict -with_nested_one_of_from_dict = WithNestedOneOf.from_dict(with_nested_one_of_dict) +with_nested_one_of_from_dict = WithNestedOneOf.model_validate(with_nested_one_of_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_client.py index bbdb918c7c5e..62440d5e858c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_client.py @@ -717,7 +717,7 @@ def __deserialize_file(self, response): content_disposition ) assert m is not None, "Unexpected 'content-disposition' header value" - filename = m.group(1) + filename = os.path.basename(m.group(1)) # Strip any directory traversal path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py index 291b5e55e353..d3c2e0c15c8d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesAnyType(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesAnyType(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesAnyType from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesAnyType from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_class.py index 4b2cc457e499..1b96696ac069 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_class.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesClass(BaseModel): """ @@ -37,53 +38,27 @@ class AdditionalPropertiesClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "map_property": obj.get("map_property"), - "map_of_map_property": obj.get("map_of_map_property") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py index 00707c3c4818..4484e38c8bef 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesObject(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py index d8049b519ed0..0dd3de45f5d3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesWithDescriptionOnly(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesWithDescriptionOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesWithDescriptionOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_super_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_super_model.py index 03f554592935..ed486fe11505 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_super_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_super_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AllOfSuperModel(BaseModel): """ @@ -36,52 +37,27 @@ class AllOfSuperModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AllOfSuperModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AllOfSuperModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_with_single_ref.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_with_single_ref.py index 44c7da9114a8..bffacd075374 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_with_single_ref.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_with_single_ref.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.single_ref_type import SingleRefType from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AllOfWithSingleRef(BaseModel): """ @@ -38,53 +39,27 @@ class AllOfWithSingleRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AllOfWithSingleRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AllOfWithSingleRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "username": obj.get("username"), - "SingleRefType": obj.get("SingleRefType") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/animal.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/animal.py index 56bec73a9ccd..6af4a155d46a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/animal.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/animal.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -60,52 +61,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Union[Cat, Dog]]: - """Create an instance of Animal from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[Cat, Dog]]: - """Create an instance of Animal from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'Cat': - return import_module("petstore_api.models.cat").Cat.from_dict(obj) - if object_type == 'Dog': - return import_module("petstore_api.models.dog").Dog.from_dict(obj) - - raise ValueError("Animal failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py index f6d277e79498..b86b03be3591 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py @@ -13,8 +13,6 @@ from __future__ import annotations -from inspect import getfullargspec -import json import pprint import re # noqa: F401 from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator @@ -22,135 +20,56 @@ from typing_extensions import Annotated from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self -from pydantic import Field +from pydantic import Field, RootModel ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] -class AnyOfColor(BaseModel): + +class AnyOfColor(RootModel[Union[List[int], str]]): """ Any of RGB array, RGBA array, or hex string. """ - # data type: List[int] - anyof_schema_1_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=3, max_length=3)]] = Field(default=None, description="RGB three element array with values 0-255.") - # data type: List[int] - anyof_schema_2_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=4, max_length=4)]] = Field(default=None, description="RGBA four element array with values 0-255.") - # data type: str - anyof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") - if TYPE_CHECKING: - actual_instance: Optional[Union[List[int], str]] = None - else: - actual_instance: Any = None - any_of_schemas: Set[str] = { "List[int]", "str" } - - model_config = { - "validate_assignment": True, - "protected_namespaces": (), - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - instance = AnyOfColor.model_construct() - error_messages = [] - # validate data type: List[int] - try: - instance.anyof_schema_1_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: List[int] - try: - instance.anyof_schema_2_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.anyof_schema_3_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return v + root: Union[List[int], str] = Field( + ... + ) + + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ + + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod def from_dict(cls, obj: Dict[str, Any]) -> Self: - return cls.from_json(json.dumps(obj)) + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - # deserialize data into List[int] - try: - # validation - instance.anyof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_1_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into List[int] - try: - # validation - instance.anyof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_2_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.anyof_schema_3_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_3_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) + return self.model_dump_json(by_alias=True, exclude_none=True) - def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py index c949e136f415..a632d3c382d6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py @@ -13,8 +13,6 @@ from __future__ import annotations -from inspect import getfullargspec -import json import pprint import re # noqa: F401 from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator @@ -23,112 +21,56 @@ from petstore_api.models.danish_pig import DanishPig from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self -from pydantic import Field +from pydantic import Field, RootModel ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] -class AnyOfPig(BaseModel): + +class AnyOfPig(RootModel[Union[BasquePig, DanishPig]]): """ AnyOfPig """ - # data type: BasquePig - anyof_schema_1_validator: Optional[BasquePig] = None - # data type: DanishPig - anyof_schema_2_validator: Optional[DanishPig] = None - if TYPE_CHECKING: - actual_instance: Optional[Union[BasquePig, DanishPig]] = None - else: - actual_instance: Any = None - any_of_schemas: Set[str] = { "BasquePig", "DanishPig" } - - model_config = { - "validate_assignment": True, - "protected_namespaces": (), - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - instance = AnyOfPig.model_construct() - error_messages = [] - # validate data type: BasquePig - if not isinstance(v, BasquePig): - error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`") - else: - return v - - # validate data type: DanishPig - if not isinstance(v, DanishPig): - error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`") - else: - return v - - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return v + root: Union[BasquePig, DanishPig] = Field( + ... + ) + + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ + + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod def from_dict(cls, obj: Dict[str, Any]) -> Self: - return cls.from_json(json.dumps(obj)) + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - # anyof_schema_1_validator: Optional[BasquePig] = None - try: - instance.actual_instance = BasquePig.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # anyof_schema_2_validator: Optional[DanishPig] = None - try: - instance.actual_instance = DanishPig.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) + return self.model_dump_json(by_alias=True, exclude_none=True) - def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_model.py index 4f8eeda66c30..7213f2a1cad9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_model.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfArrayOfModel(BaseModel): """ @@ -37,64 +38,27 @@ class ArrayOfArrayOfModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in another_property (list of list) - _items = [] - if self.another_property: - for _item_another_property in self.another_property: - if _item_another_property: - _items.append( - [_inner_item.to_dict() for _inner_item in _item_another_property if _inner_item is not None] - ) - _dict['another_property'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "another_property": [ - [Tag.from_dict(_inner_item) for _inner_item in _item] - for _item in obj["another_property"] - ] if obj.get("another_property") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_number_only.py index 02b0f6d657f4..e477a9006153 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfArrayOfNumberOnly(BaseModel): """ @@ -36,52 +37,27 @@ class ArrayOfArrayOfNumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfNumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfNumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "ArrayArrayNumber": obj.get("ArrayArrayNumber") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_number_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_number_only.py index b22632b0ce4d..692a8662c7b5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfNumberOnly(BaseModel): """ @@ -36,52 +37,27 @@ class ArrayOfNumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfNumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfNumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "ArrayNumber": obj.get("ArrayNumber") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_test.py index e8f8acf67cc0..c8b3e175de72 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_test.py @@ -22,7 +22,8 @@ from typing_extensions import Annotated from petstore_api.models.read_only_first import ReadOnlyFirst from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayTest(BaseModel): """ @@ -41,67 +42,27 @@ class ArrayTest(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in array_array_of_model (list of list) - _items = [] - if self.array_array_of_model: - for _item_array_array_of_model in self.array_array_of_model: - if _item_array_array_of_model: - _items.append( - [_inner_item.to_dict() for _inner_item in _item_array_array_of_model if _inner_item is not None] - ) - _dict['array_array_of_model'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "array_of_string": obj.get("array_of_string"), - "array_of_nullable_float": obj.get("array_of_nullable_float"), - "array_array_of_integer": obj.get("array_array_of_integer"), - "array_array_of_model": [ - [ReadOnlyFirst.from_dict(_inner_item) for _inner_item in _item] - for _item in obj["array_array_of_model"] - ] if obj.get("array_array_of_model") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/base_discriminator.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/base_discriminator.py index f13c270b56b5..6946039d34d2 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/base_discriminator.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/base_discriminator.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -59,52 +60,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Union[PrimitiveString, Info]]: - """Create an instance of BaseDiscriminator from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[PrimitiveString, Info]]: - """Create an instance of BaseDiscriminator from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'PrimitiveString': - return import_module("petstore_api.models.primitive_string").PrimitiveString.from_dict(obj) - if object_type == 'Info': - return import_module("petstore_api.models.info").Info.from_dict(obj) - - raise ValueError("BaseDiscriminator failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/basque_pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/basque_pig.py index a1f32a6edcfc..cc3c77e89471 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/basque_pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/basque_pig.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class BasquePig(BaseModel): """ @@ -37,53 +38,27 @@ class BasquePig(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of BasquePig from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of BasquePig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/bathing.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/bathing.py index 088e6ad3b873..8b376f1c1ac1 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/bathing.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/bathing.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Bathing(BaseModel): """ Bathing """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning_deep'] = Field( + ..., + description="task_name of the Bathing", + alias="task_name" + ) + function_name: Literal['care_nourish'] = Field( + ..., + description="function_name of the Bathing", + alias="function_name" + ) content: StrictStr __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -52,54 +61,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Bathing from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Bathing from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/capitalization.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/capitalization.py index b3c20af54440..cf44f6a8d7ff 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/capitalization.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/capitalization.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Capitalization(BaseModel): """ @@ -41,57 +42,27 @@ class Capitalization(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Capitalization from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Capitalization from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "smallCamel": obj.get("smallCamel"), - "CapitalCamel": obj.get("CapitalCamel"), - "small_Snake": obj.get("small_Snake"), - "Capital_Snake": obj.get("Capital_Snake"), - "SCA_ETH_Flow_Points": obj.get("SCA_ETH_Flow_Points"), - "ATT_NAME": obj.get("ATT_NAME") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/cat.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/cat.py index 0c2c9788dca3..dd9ba455914c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/cat.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/cat.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Cat(Animal): """ @@ -37,54 +38,27 @@ class Cat(Animal): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Cat from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Cat from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") if obj.get("color") is not None else 'red', - "declawed": obj.get("declawed") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/category.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/category.py index dcc6247b5ac7..3b46a4d7e44e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/category.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/category.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Category(BaseModel): """ @@ -37,53 +38,27 @@ class Category(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Category from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Category from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") if obj.get("name") is not None else 'default-name' - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_all_of_ref.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_all_of_ref.py index f98247ae0fb5..f3525d486eee 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_all_of_ref.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_all_of_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CircularAllOfRef(BaseModel): """ @@ -37,61 +38,28 @@ class CircularAllOfRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CircularAllOfRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in second_circular_all_of_ref (list) - _items = [] - if self.second_circular_all_of_ref: - for _item_second_circular_all_of_ref in self.second_circular_all_of_ref: - if _item_second_circular_all_of_ref: - _items.append(_item_second_circular_all_of_ref.to_dict()) - _dict['secondCircularAllOfRef'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CircularAllOfRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name"), - "secondCircularAllOfRef": [SecondCircularAllOfRef.from_dict(_item) for _item in obj["secondCircularAllOfRef"]] if obj.get("secondCircularAllOfRef") is not None else None - }) - return _obj from petstore_api.models.second_circular_all_of_ref import SecondCircularAllOfRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_reference_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_reference_model.py index 3b2854caaac2..51a3cf9107a7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_reference_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_reference_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CircularReferenceModel(BaseModel): """ @@ -37,57 +38,28 @@ class CircularReferenceModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CircularReferenceModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested - if self.nested: - _dict['nested'] = self.nested.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CircularReferenceModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested": FirstRef.from_dict(obj["nested"]) if obj.get("nested") is not None else None - }) - return _obj from petstore_api.models.first_ref import FirstRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/class_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/class_model.py index 6def0e52d146..6988fc984136 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/class_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/class_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ClassModel(BaseModel): """ @@ -36,52 +37,27 @@ class ClassModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ClassModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ClassModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_class": obj.get("_class") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/client.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/client.py index 1c12c9a145c8..f7b9f517226d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/client.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/client.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Client(BaseModel): """ @@ -36,52 +37,27 @@ class Client(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Client from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Client from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "client": obj.get("client") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py index bb740fb597d4..5197fe58ecc6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py @@ -18,150 +18,55 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional from typing_extensions import Annotated -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] -class Color(BaseModel): +class Color(RootModel[Union[List[int], str]]): """ RGB array, RGBA array, or hex string. """ - # data type: List[int] - oneof_schema_1_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=3, max_length=3)]] = Field(default=None, description="RGB three element array with values 0-255.") - # data type: List[int] - oneof_schema_2_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=4, max_length=4)]] = Field(default=None, description="RGBA four element array with values 0-255.") - # data type: str - oneof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") - actual_instance: Optional[Union[List[int], str]] = None - one_of_schemas: Set[str] = { "List[int]", "str" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[List[int], str, None] = Field( + None ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - if v is None: - return v - - instance = Color.model_construct() - error_messages = [] - match = 0 - # validate data type: List[int] - try: - instance.oneof_schema_1_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: List[int] - try: - instance.oneof_schema_2_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.oneof_schema_3_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: Optional[str]) -> Self: + def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - if json_str is None: - return instance - - error_messages = [] - match = 0 - - # deserialize data into List[int] - try: - # validation - instance.oneof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_1_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into List[int] - try: - # validation - instance.oneof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_2_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.oneof_schema_3_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_3_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature.py index 2ed3aa42bf99..f4509fd781b3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature.py @@ -22,7 +22,8 @@ from typing import Any, ClassVar, Dict, List, Union from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -60,53 +61,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[HuntingDog]]: - """Create an instance of Creature from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of info - if self.info: - _dict['info'] = self.info.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[HuntingDog]]: - """Create an instance of Creature from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'HuntingDog': - return import_module("petstore_api.models.hunting_dog").HuntingDog.from_dict(obj) - - raise ValueError("Creature failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature_info.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature_info.py index e7927446c238..46da1157c838 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature_info.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature_info.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CreatureInfo(BaseModel): """ @@ -36,52 +37,27 @@ class CreatureInfo(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CreatureInfo from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CreatureInfo from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/danish_pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/danish_pig.py index 061e16a486a5..d8dda939f40e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/danish_pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/danish_pig.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DanishPig(BaseModel): """ @@ -37,53 +38,27 @@ class DanishPig(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DanishPig from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DanishPig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "size": obj.get("size") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/deprecated_object.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/deprecated_object.py index bb4747a1e18c..225295ec6a18 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/deprecated_object.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/deprecated_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DeprecatedObject(BaseModel): """ @@ -36,52 +37,27 @@ class DeprecatedObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DeprecatedObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DeprecatedObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/discriminator_all_of_sub.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/discriminator_all_of_sub.py index 2e8d4a6d7633..e488c3d8a0ba 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/discriminator_all_of_sub.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/discriminator_all_of_sub.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List from petstore_api.models.discriminator_all_of_super import DiscriminatorAllOfSuper from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DiscriminatorAllOfSub(DiscriminatorAllOfSuper): """ @@ -36,52 +37,27 @@ class DiscriminatorAllOfSub(DiscriminatorAllOfSuper): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DiscriminatorAllOfSub from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DiscriminatorAllOfSub from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "elementType": obj.get("elementType") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/discriminator_all_of_super.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/discriminator_all_of_super.py index ee910f90ea69..476d44bbb9b0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/discriminator_all_of_super.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/discriminator_all_of_super.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -58,50 +59,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Union[DiscriminatorAllOfSub]]: - """Create an instance of DiscriminatorAllOfSuper from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[DiscriminatorAllOfSub]]: - """Create an instance of DiscriminatorAllOfSuper from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'DiscriminatorAllOfSub': - return import_module("petstore_api.models.discriminator_all_of_sub").DiscriminatorAllOfSub.from_dict(obj) - - raise ValueError("DiscriminatorAllOfSuper failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dog.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dog.py index a0f4ed786b4e..1cdf9778bb2d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dog.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dog.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Dog(Animal): """ @@ -37,54 +38,27 @@ class Dog(Animal): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Dog from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Dog from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") if obj.get("color") is not None else 'red', - "breed": obj.get("breed") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dummy_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dummy_model.py index 3050cbf66dc4..230684d30487 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dummy_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dummy_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DummyModel(BaseModel): """ @@ -37,57 +38,28 @@ class DummyModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DummyModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of self_ref - if self.self_ref: - _dict['self_ref'] = self.self_ref.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DummyModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "self_ref": SelfReferenceModel.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None - }) - return _obj from petstore_api.models.self_reference_model import SelfReferenceModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py index 68ceb962b03e..2ffde2d8e823 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py @@ -20,14 +20,21 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumArrays(BaseModel): """ EnumArrays """ # noqa: E501 - just_symbol: Optional[StrictStr] = None - array_enum: Optional[List[StrictStr]] = None + just_symbol: Optional[Literal['>=', '$']] = Field( + None, + description="just_symbol of the EnumArrays" + ) + array_enum: Optional[List[Literal['fish', 'crab']]] = Field( + None, + description="array_enum of the EnumArrays" + ) __properties: ClassVar[List[str]] = ["just_symbol", "array_enum"] @field_validator('just_symbol') @@ -58,53 +65,27 @@ def array_enum_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumArrays from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumArrays from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "just_symbol": obj.get("just_symbol"), - "array_enum": obj.get("array_enum") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_ref_with_default_value.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_ref_with_default_value.py index 9d97e3fd16d4..0f238270fd0c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_ref_with_default_value.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_ref_with_default_value.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.data_output_format import DataOutputFormat from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumRefWithDefaultValue(BaseModel): """ @@ -37,52 +38,27 @@ class EnumRefWithDefaultValue(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumRefWithDefaultValue from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumRefWithDefaultValue from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "report_format": obj.get("report_format") if obj.get("report_format") is not None else DataOutputFormat.JSON - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py index b7e6ec36230f..d59763c5a82d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py @@ -26,19 +26,43 @@ from petstore_api.models.outer_enum_integer import OuterEnumInteger from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumTest(BaseModel): """ EnumTest """ # noqa: E501 - enum_string: Optional[StrictStr] = None - enum_string_required: StrictStr - enum_integer_default: Optional[StrictInt] = 5 - enum_integer: Optional[StrictInt] = None - enum_number: Optional[float] = None - enum_string_single_member: Optional[StrictStr] = None - enum_integer_single_member: Optional[StrictInt] = None + enum_string: Optional[Literal['UPPER', 'lower', '']] = Field( + None, + description="enum_string of the EnumTest" + ) + enum_string_required: Literal['UPPER', 'lower', ''] = Field( + ..., + description="enum_string_required of the EnumTest" + ) + enum_integer_default: Optional[Literal[1, 5, 14]] = Field( + None, + description="enum_integer_default of the EnumTest" + ) + enum_integer: Optional[Literal[1, -1]] = Field( + None, + description="enum_integer of the EnumTest" + ) + enum_number: Optional[Literal[1.1, -1.2]] = Field( + None, + description="enum_number of the EnumTest" + ) + enum_string_single_member: Literal['abc'] = Field( + None, + description="enum_string_single_member of the EnumTest", + alias="enum_string_single_member" + ) + enum_integer_single_member: Literal['100'] = Field( + None, + description="enum_integer_single_member of the EnumTest", + alias="enum_integer_single_member" + ) outer_enum: Optional[OuterEnum] = Field(default=None, alias="outerEnum") outer_enum_integer: Optional[OuterEnumInteger] = Field(default=None, alias="outerEnumInteger") outer_enum_default_value: Optional[OuterEnumDefaultValue] = Field(default=OuterEnumDefaultValue.PLACED, alias="outerEnumDefaultValue") @@ -121,69 +145,27 @@ def enum_integer_single_member_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if outer_enum (nullable) is None - # and model_fields_set contains the field - if self.outer_enum is None and "outer_enum" in self.model_fields_set: - _dict['outerEnum'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "enum_string": obj.get("enum_string"), - "enum_string_required": obj.get("enum_string_required"), - "enum_integer_default": obj.get("enum_integer_default") if obj.get("enum_integer_default") is not None else 5, - "enum_integer": obj.get("enum_integer"), - "enum_number": obj.get("enum_number"), - "enum_string_single_member": obj.get("enum_string_single_member"), - "enum_integer_single_member": obj.get("enum_integer_single_member"), - "outerEnum": obj.get("outerEnum"), - "outerEnumInteger": obj.get("outerEnumInteger"), - "outerEnumDefaultValue": obj.get("outerEnumDefaultValue") if obj.get("outerEnumDefaultValue") is not None else OuterEnumDefaultValue.PLACED, - "outerEnumIntegerDefaultValue": obj.get("outerEnumIntegerDefaultValue") if obj.get("outerEnumIntegerDefaultValue") is not None else OuterEnumIntegerDefaultValue.NUMBER_0, - "enumNumberVendorExt": obj.get("enumNumberVendorExt"), - "enumStringVendorExt": obj.get("enumStringVendorExt") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/feeding.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/feeding.py index 1183b314fdd0..1f6ff4555236 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/feeding.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/feeding.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Feeding(BaseModel): """ Feeding """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning'] = Field( + ..., + description="task_name of the Feeding", + alias="task_name" + ) + function_name: Literal['care_nourish'] = Field( + ..., + description="function_name of the Feeding", + alias="function_name" + ) content: StrictStr __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -52,54 +61,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Feeding from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Feeding from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file.py index 0ecacf44bb8e..213a82e08c80 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class File(BaseModel): """ @@ -36,52 +37,27 @@ class File(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of File from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of File from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "sourceURI": obj.get("sourceURI") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file_schema_test_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file_schema_test_class.py index c533c0777b24..7fe7d4e48409 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file_schema_test_class.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.file import File from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FileSchemaTestClass(BaseModel): """ @@ -38,63 +39,27 @@ class FileSchemaTestClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FileSchemaTestClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of file - if self.file: - _dict['file'] = self.file.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in files (list) - _items = [] - if self.files: - for _item_files in self.files: - if _item_files: - _items.append(_item_files.to_dict()) - _dict['files'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FileSchemaTestClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "file": File.from_dict(obj["file"]) if obj.get("file") is not None else None, - "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/first_ref.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/first_ref.py index 6aa0f722d874..77fba27b8ba3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/first_ref.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/first_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FirstRef(BaseModel): """ @@ -37,57 +38,28 @@ class FirstRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FirstRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of self_ref - if self.self_ref: - _dict['self_ref'] = self.self_ref.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FirstRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "self_ref": SecondRef.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None - }) - return _obj from petstore_api.models.second_ref import SecondRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo.py index 67b29f1ab87c..902c6ccbb7f6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Foo(BaseModel): """ @@ -36,52 +37,27 @@ class Foo(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Foo from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Foo from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar") if obj.get("bar") is not None else 'bar' - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo_get_default_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo_get_default_response.py index ae191aad80a8..51b1e9d1a1ed 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo_get_default_response.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo_get_default_response.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.foo import Foo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FooGetDefaultResponse(BaseModel): """ @@ -37,55 +38,27 @@ class FooGetDefaultResponse(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FooGetDefaultResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of string - if self.string: - _dict['string'] = self.string.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FooGetDefaultResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "string": Foo.from_dict(obj["string"]) if obj.get("string") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/format_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/format_test.py index 8d70a96f3a7c..dd2537299ef2 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/format_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/format_test.py @@ -24,7 +24,8 @@ from typing_extensions import Annotated from uuid import UUID from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FormatTest(BaseModel): """ @@ -96,68 +97,27 @@ def pattern_with_digits_and_delimiter_validate_regular_expression(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FormatTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FormatTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "integer": obj.get("integer"), - "int32": obj.get("int32"), - "int64": obj.get("int64"), - "number": obj.get("number"), - "float": obj.get("float"), - "double": obj.get("double"), - "decimal": obj.get("decimal"), - "string": obj.get("string"), - "string_with_double_quote_pattern": obj.get("string_with_double_quote_pattern"), - "byte": obj.get("byte"), - "binary": obj.get("binary"), - "date": obj.get("date"), - "dateTime": obj.get("dateTime"), - "uuid": obj.get("uuid"), - "password": obj.get("password"), - "pattern_with_digits": obj.get("pattern_with_digits"), - "pattern_with_digits_and_delimiter": obj.get("pattern_with_digits_and_delimiter") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/has_only_read_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/has_only_read_only.py index 2137bc880484..f0721e724492 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/has_only_read_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HasOnlyReadOnly(BaseModel): """ @@ -37,57 +38,27 @@ class HasOnlyReadOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HasOnlyReadOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * OpenAPI `readOnly` fields are excluded. - """ - excluded_fields: Set[str] = set([ - "bar", - "foo", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HasOnlyReadOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar"), - "foo": obj.get("foo") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/health_check_result.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/health_check_result.py index 4dbdd852097f..007ebd7c3fba 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/health_check_result.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/health_check_result.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HealthCheckResult(BaseModel): """ @@ -36,57 +37,27 @@ class HealthCheckResult(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HealthCheckResult from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if nullable_message (nullable) is None - # and model_fields_set contains the field - if self.nullable_message is None and "nullable_message" in self.model_fields_set: - _dict['NullableMessage'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HealthCheckResult from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "NullableMessage": obj.get("NullableMessage") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/hunting_dog.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/hunting_dog.py index cd678616f62f..0bd4255928fb 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/hunting_dog.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/hunting_dog.py @@ -22,7 +22,8 @@ from petstore_api.models.creature import Creature from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HuntingDog(Creature): """ @@ -38,57 +39,27 @@ class HuntingDog(Creature): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HuntingDog from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of info - if self.info: - _dict['info'] = self.info.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HuntingDog from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "info": CreatureInfo.from_dict(obj["info"]) if obj.get("info") is not None else None, - "type": obj.get("type"), - "isTrained": obj.get("isTrained") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/info.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/info.py index 5a15b5f9f52f..da9fc38935f9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/info.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/info.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.base_discriminator import BaseDiscriminator from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Info(BaseDiscriminator): """ @@ -37,56 +38,27 @@ class Info(BaseDiscriminator): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Info from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of val - if self.val: - _dict['val'] = self.val.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Info from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_typeName": obj.get("_typeName"), - "val": BaseDiscriminator.from_dict(obj["val"]) if obj.get("val") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/inner_dict_with_property.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/inner_dict_with_property.py index 27816b995f53..8c1f33db2d78 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/inner_dict_with_property.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/inner_dict_with_property.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class InnerDictWithProperty(BaseModel): """ @@ -36,52 +37,27 @@ class InnerDictWithProperty(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of InnerDictWithProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of InnerDictWithProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "aProperty": obj.get("aProperty") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/input_all_of.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/input_all_of.py index 63870cca83ed..9c3716d502b0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/input_all_of.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/input_all_of.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class InputAllOf(BaseModel): """ @@ -37,64 +38,27 @@ class InputAllOf(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of InputAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in some_data (dict) - _field_dict = {} - if self.some_data: - for _key_some_data in self.some_data: - if self.some_data[_key_some_data]: - _field_dict[_key_some_data] = self.some_data[_key_some_data].to_dict() - _dict['some_data'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of InputAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "some_data": dict( - (_k, Tag.from_dict(_v)) - for _k, _v in obj["some_data"].items() - ) - if obj.get("some_data") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..c66bf1ab9772 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py @@ -18,127 +18,55 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional from typing_extensions import Annotated -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] -class IntOrString(BaseModel): +class IntOrString(RootModel[Union[int, str]]): """ IntOrString """ - # data type: int - oneof_schema_1_validator: Optional[Annotated[int, Field(strict=True, ge=10)]] = None - # data type: str - oneof_schema_2_validator: Optional[StrictStr] = None - actual_instance: Optional[Union[int, str]] = None - one_of_schemas: Set[str] = { "int", "str" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[int, str] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = IntOrString.model_construct() - error_messages = [] - match = 0 - # validate data type: int - try: - instance.oneof_schema_1_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.oneof_schema_2_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into int - try: - # validation - instance.oneof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_1_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.oneof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_2_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list_class.py index ab12a7fac521..be0a9543d04d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list_class.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ListClass(BaseModel): """ @@ -36,52 +37,27 @@ class ListClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ListClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ListClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "123-list": obj.get("123-list") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_of_array_of_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_of_array_of_model.py index a9bd000ad9ba..5ed090e91592 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_of_array_of_model.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MapOfArrayOfModel(BaseModel): """ @@ -37,68 +38,27 @@ class MapOfArrayOfModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MapOfArrayOfModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in shop_id_to_org_online_lip_map (dict of array) - _field_dict_of_array = {} - if self.shop_id_to_org_online_lip_map: - for _key_shop_id_to_org_online_lip_map in self.shop_id_to_org_online_lip_map: - if self.shop_id_to_org_online_lip_map[_key_shop_id_to_org_online_lip_map] is not None: - _field_dict_of_array[_key_shop_id_to_org_online_lip_map] = [ - _item.to_dict() for _item in self.shop_id_to_org_online_lip_map[_key_shop_id_to_org_online_lip_map] - ] - _dict['shopIdToOrgOnlineLipMap'] = _field_dict_of_array - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MapOfArrayOfModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "shopIdToOrgOnlineLipMap": dict( - (_k, - [Tag.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("shopIdToOrgOnlineLipMap", {}).items() - ) - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py index 2a056ab5532a..05677731440d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py @@ -20,14 +20,18 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MapTest(BaseModel): """ MapTest """ # noqa: E501 map_map_of_string: Optional[Dict[str, Dict[str, StrictStr]]] = None - map_of_enum_string: Optional[Dict[str, StrictStr]] = None + map_of_enum_string: Optional[Literal['UPPER', 'lower']] = Field( + None, + description="map_of_enum_string of the MapTest" + ) direct_map: Optional[Dict[str, StrictBool]] = None indirect_map: Optional[Dict[str, StrictBool]] = None __properties: ClassVar[List[str]] = ["map_map_of_string", "map_of_enum_string", "direct_map", "indirect_map"] @@ -50,55 +54,27 @@ def map_of_enum_string_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MapTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MapTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "map_map_of_string": obj.get("map_map_of_string"), - "map_of_enum_string": obj.get("map_of_enum_string"), - "direct_map": obj.get("direct_map"), - "indirect_map": obj.get("indirect_map") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/mixed_properties_and_additional_properties_class.py index 46998dfb5c68..141ee7f93eb0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -23,7 +23,8 @@ from uuid import UUID from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): """ @@ -41,66 +42,27 @@ class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in map (dict) - _field_dict = {} - if self.map: - for _key_map in self.map: - if self.map[_key_map]: - _field_dict[_key_map] = self.map[_key_map].to_dict() - _dict['map'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "uuid": obj.get("uuid"), - "dateTime": obj.get("dateTime"), - "map": dict( - (_k, Animal.from_dict(_v)) - for _k, _v in obj["map"].items() - ) - if obj.get("map") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model200_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model200_response.py index d6012c57fbd7..8466c296265f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model200_response.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model200_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Model200Response(BaseModel): """ @@ -37,53 +38,27 @@ class Model200Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Model200Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Model200Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name"), - "class": obj.get("class") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_api_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_api_response.py index 005c77823bef..7c9a05eb1df9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_api_response.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_api_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelApiResponse(BaseModel): """ @@ -38,54 +39,27 @@ class ModelApiResponse(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelApiResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelApiResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "code": obj.get("code"), - "type": obj.get("type"), - "message": obj.get("message") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_field.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_field.py index 9e36a6ac7e48..ab4c4b0c1102 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_field.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_field.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelField(BaseModel): """ @@ -36,52 +37,27 @@ class ModelField(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelField from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelField from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "field": obj.get("field") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_return.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_return.py index a8c0f53f6c19..41a8af9a1a6d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_return.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_return.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelReturn(BaseModel): """ @@ -36,52 +37,27 @@ class ModelReturn(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelReturn from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelReturn from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "return": obj.get("return") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/multi_arrays.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/multi_arrays.py index 177a8359468f..2bdb5ddfeb4e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/multi_arrays.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/multi_arrays.py @@ -22,7 +22,8 @@ from petstore_api.models.file import File from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MultiArrays(BaseModel): """ @@ -39,67 +40,27 @@ class MultiArrays(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MultiArrays from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - # override the default output from pydantic by calling `to_dict()` of each item in files (list) - _items = [] - if self.files: - for _item_files in self.files: - if _item_files: - _items.append(_item_files.to_dict()) - _dict['files'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MultiArrays from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/name.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/name.py index f33b2ecb18be..0c6efd791f89 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/name.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/name.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Name(BaseModel): """ @@ -39,59 +40,27 @@ class Name(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Name from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * OpenAPI `readOnly` fields are excluded. - """ - excluded_fields: Set[str] = set([ - "snake_case", - "var_123_number", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Name from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name"), - "snake_case": obj.get("snake_case"), - "property": obj.get("property"), - "123Number": obj.get("123Number") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py index 9d1414954830..d1780fadb477 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NullableClass(BaseModel): """ @@ -50,131 +51,27 @@ class NullableClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NullableClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if required_integer_prop (nullable) is None - # and model_fields_set contains the field - if self.required_integer_prop is None and "required_integer_prop" in self.model_fields_set: - _dict['required_integer_prop'] = None - - # set to None if integer_prop (nullable) is None - # and model_fields_set contains the field - if self.integer_prop is None and "integer_prop" in self.model_fields_set: - _dict['integer_prop'] = None - - # set to None if number_prop (nullable) is None - # and model_fields_set contains the field - if self.number_prop is None and "number_prop" in self.model_fields_set: - _dict['number_prop'] = None - - # set to None if boolean_prop (nullable) is None - # and model_fields_set contains the field - if self.boolean_prop is None and "boolean_prop" in self.model_fields_set: - _dict['boolean_prop'] = None - - # set to None if string_prop (nullable) is None - # and model_fields_set contains the field - if self.string_prop is None and "string_prop" in self.model_fields_set: - _dict['string_prop'] = None - - # set to None if date_prop (nullable) is None - # and model_fields_set contains the field - if self.date_prop is None and "date_prop" in self.model_fields_set: - _dict['date_prop'] = None - - # set to None if datetime_prop (nullable) is None - # and model_fields_set contains the field - if self.datetime_prop is None and "datetime_prop" in self.model_fields_set: - _dict['datetime_prop'] = None - - # set to None if array_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.array_nullable_prop is None and "array_nullable_prop" in self.model_fields_set: - _dict['array_nullable_prop'] = None - - # set to None if array_and_items_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.array_and_items_nullable_prop is None and "array_and_items_nullable_prop" in self.model_fields_set: - _dict['array_and_items_nullable_prop'] = None - - # set to None if object_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.object_nullable_prop is None and "object_nullable_prop" in self.model_fields_set: - _dict['object_nullable_prop'] = None - - # set to None if object_and_items_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.object_and_items_nullable_prop is None and "object_and_items_nullable_prop" in self.model_fields_set: - _dict['object_and_items_nullable_prop'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NullableClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "required_integer_prop": obj.get("required_integer_prop"), - "integer_prop": obj.get("integer_prop"), - "number_prop": obj.get("number_prop"), - "boolean_prop": obj.get("boolean_prop"), - "string_prop": obj.get("string_prop"), - "date_prop": obj.get("date_prop"), - "datetime_prop": obj.get("datetime_prop"), - "array_nullable_prop": obj.get("array_nullable_prop"), - "array_and_items_nullable_prop": obj.get("array_and_items_nullable_prop"), - "array_items_nullable": obj.get("array_items_nullable"), - "object_nullable_prop": obj.get("object_nullable_prop"), - "object_and_items_nullable_prop": obj.get("object_and_items_nullable_prop"), - "object_items_nullable": obj.get("object_items_nullable") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_property.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_property.py index 2324745d7dd1..910b6cd762ae 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_property.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_property.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NullableProperty(BaseModel): """ @@ -48,58 +49,27 @@ def name_validate_regular_expression(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NullableProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if name (nullable) is None - # and model_fields_set contains the field - if self.name is None and "name" in self.model_fields_set: - _dict['name'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NullableProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/number_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/number_only.py index 18c3ec953080..3dc8a40ea29a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/number_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NumberOnly(BaseModel): """ @@ -36,52 +37,27 @@ class NumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "JustNumber": obj.get("JustNumber") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_to_test_additional_properties.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_to_test_additional_properties.py index 22b8bd401a1c..d8e224dbfeda 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_to_test_additional_properties.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_to_test_additional_properties.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ObjectToTestAdditionalProperties(BaseModel): """ @@ -36,52 +37,27 @@ class ObjectToTestAdditionalProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ObjectToTestAdditionalProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ObjectToTestAdditionalProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "property": obj.get("property") if obj.get("property") is not None else False - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_with_deprecated_fields.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_with_deprecated_fields.py index 4d76d9f5fc72..41dfcf6f1019 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_with_deprecated_fields.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_with_deprecated_fields.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.deprecated_object import DeprecatedObject from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ObjectWithDeprecatedFields(BaseModel): """ @@ -40,58 +41,27 @@ class ObjectWithDeprecatedFields(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ObjectWithDeprecatedFields from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of deprecated_ref - if self.deprecated_ref: - _dict['deprecatedRef'] = self.deprecated_ref.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ObjectWithDeprecatedFields from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "uuid": obj.get("uuid"), - "id": obj.get("id"), - "deprecatedRef": DeprecatedObject.from_dict(obj["deprecatedRef"]) if obj.get("deprecatedRef") is not None else None, - "bars": obj.get("bars") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py index f742027e088a..8aed7ad5e761 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Order(BaseModel): """ @@ -31,7 +32,10 @@ class Order(BaseModel): pet_id: Optional[StrictInt] = Field(default=None, alias="petId") quantity: Optional[StrictInt] = None ship_date: Optional[datetime] = Field(default=None, alias="shipDate") - status: Optional[StrictStr] = Field(default=None, description="Order Status") + status: Optional[Literal['placed', 'approved', 'delivered']] = Field( + None, + description="Order Status" + ) complete: Optional[StrictBool] = False __properties: ClassVar[List[str]] = ["id", "petId", "quantity", "shipDate", "status", "complete"] @@ -52,57 +56,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Order from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Order from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "petId": obj.get("petId"), - "quantity": obj.get("quantity"), - "shipDate": obj.get("shipDate"), - "status": obj.get("status"), - "complete": obj.get("complete") if obj.get("complete") is not None else False - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_composite.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_composite.py index 6a82d49970cb..041590afed6c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_composite.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_composite.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class OuterComposite(BaseModel): """ @@ -38,54 +39,27 @@ class OuterComposite(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of OuterComposite from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of OuterComposite from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "my_number": obj.get("my_number"), - "my_string": obj.get("my_string"), - "my_boolean": obj.get("my_boolean") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_object_with_enum_property.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_object_with_enum_property.py index 4f453c2a8d0c..f53f359d1758 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_object_with_enum_property.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_object_with_enum_property.py @@ -22,7 +22,8 @@ from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_integer import OuterEnumInteger from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class OuterObjectWithEnumProperty(BaseModel): """ @@ -39,58 +40,27 @@ class OuterObjectWithEnumProperty(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of OuterObjectWithEnumProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if str_value (nullable) is None - # and model_fields_set contains the field - if self.str_value is None and "str_value" in self.model_fields_set: - _dict['str_value'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of OuterObjectWithEnumProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "str_value": obj.get("str_value"), - "value": obj.get("value") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent.py index 5986da45ab04..4016ba494b38 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Parent(BaseModel): """ @@ -37,64 +38,27 @@ class Parent(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Parent from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) - _field_dict = {} - if self.optional_dict: - for _key_optional_dict in self.optional_dict: - if self.optional_dict[_key_optional_dict]: - _field_dict[_key_optional_dict] = self.optional_dict[_key_optional_dict].to_dict() - _dict['optionalDict'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Parent from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "optionalDict": dict( - (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj["optionalDict"].items() - ) - if obj.get("optionalDict") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent_with_optional_dict.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent_with_optional_dict.py index 84445b64043a..513e164538ee 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent_with_optional_dict.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent_with_optional_dict.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ParentWithOptionalDict(BaseModel): """ @@ -37,64 +38,27 @@ class ParentWithOptionalDict(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ParentWithOptionalDict from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) - _field_dict = {} - if self.optional_dict: - for _key_optional_dict in self.optional_dict: - if self.optional_dict[_key_optional_dict]: - _field_dict[_key_optional_dict] = self.optional_dict[_key_optional_dict].to_dict() - _dict['optionalDict'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ParentWithOptionalDict from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "optionalDict": dict( - (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj["optionalDict"].items() - ) - if obj.get("optionalDict") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py index be47c3b1a894..d399f6ba14aa 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py @@ -23,7 +23,8 @@ from petstore_api.models.category import Category from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Pet(BaseModel): """ @@ -34,7 +35,10 @@ class Pet(BaseModel): name: StrictStr photo_urls: Annotated[List[StrictStr], Field(min_length=0)] = Field(alias="photoUrls") tags: Optional[List[Tag]] = None - status: Optional[StrictStr] = Field(default=None, description="pet status in the store") + status: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) __properties: ClassVar[List[str]] = ["id", "category", "name", "photoUrls", "tags", "status"] @field_validator('status') @@ -54,67 +58,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Pet from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of category - if self.category: - _dict['category'] = self.category.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Pet from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, - "name": obj.get("name"), - "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "status": obj.get("status") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py index b3a759e89b7b..6646e6d477cd 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py @@ -19,122 +19,55 @@ from typing import Any, List, Optional from petstore_api.models.basque_pig import BasquePig from petstore_api.models.danish_pig import DanishPig -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] -class Pig(BaseModel): +class Pig(RootModel[Union[BasquePig, DanishPig]]): """ Pig """ - # data type: BasquePig - oneof_schema_1_validator: Optional[BasquePig] = None - # data type: DanishPig - oneof_schema_2_validator: Optional[DanishPig] = None - actual_instance: Optional[Union[BasquePig, DanishPig]] = None - one_of_schemas: Set[str] = { "BasquePig", "DanishPig" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[BasquePig, DanishPig] = Field( + ..., discriminator="class_name" ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - discriminator_value_class_map: Dict[str, str] = { - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = Pig.model_construct() - error_messages = [] - match = 0 - # validate data type: BasquePig - if not isinstance(v, BasquePig): - error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`") - else: - match += 1 - # validate data type: DanishPig - if not isinstance(v, DanishPig): - error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into BasquePig - try: - instance.actual_instance = BasquePig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DanishPig - try: - instance.actual_instance = DanishPig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pony_sizes.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pony_sizes.py index 00bd38659577..61d969cf2183 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pony_sizes.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pony_sizes.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.type import Type from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PonySizes(BaseModel): """ @@ -37,52 +38,27 @@ class PonySizes(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PonySizes from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PonySizes from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "type": obj.get("type") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/poop_cleaning.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/poop_cleaning.py index 047cf0d481a9..bd74546967aa 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/poop_cleaning.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/poop_cleaning.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PoopCleaning(BaseModel): """ PoopCleaning """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning'] = Field( + ..., + description="task_name of the PoopCleaning", + alias="task_name" + ) + function_name: Literal['care'] = Field( + ..., + description="function_name of the PoopCleaning", + alias="function_name" + ) content: StrictStr __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -52,54 +61,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PoopCleaning from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PoopCleaning from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/primitive_string.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/primitive_string.py index 5a7065597861..33d2f42d10c4 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/primitive_string.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/primitive_string.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.base_discriminator import BaseDiscriminator from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PrimitiveString(BaseDiscriminator): """ @@ -37,53 +38,27 @@ class PrimitiveString(BaseDiscriminator): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PrimitiveString from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PrimitiveString from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_typeName": obj.get("_typeName"), - "_value": obj.get("_value") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_map.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_map.py index 940016a86a72..fb4f8fc046c3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_map.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_map.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PropertyMap(BaseModel): """ @@ -37,64 +38,27 @@ class PropertyMap(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PropertyMap from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in some_data (dict) - _field_dict = {} - if self.some_data: - for _key_some_data in self.some_data: - if self.some_data[_key_some_data]: - _field_dict[_key_some_data] = self.some_data[_key_some_data].to_dict() - _dict['some_data'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PropertyMap from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "some_data": dict( - (_k, Tag.from_dict(_v)) - for _k, _v in obj["some_data"].items() - ) - if obj.get("some_data") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_name_collision.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_name_collision.py index 0eb56422b648..4a65d64d95ac 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_name_collision.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_name_collision.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PropertyNameCollision(BaseModel): """ @@ -38,54 +39,27 @@ class PropertyNameCollision(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PropertyNameCollision from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PropertyNameCollision from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_type": obj.get("_type"), - "type": obj.get("type"), - "type_": obj.get("type_") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/read_only_first.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/read_only_first.py index c9f4fc6c0df9..5e625cb6d272 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/read_only_first.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/read_only_first.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ReadOnlyFirst(BaseModel): """ @@ -37,55 +38,27 @@ class ReadOnlyFirst(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ReadOnlyFirst from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - """ - excluded_fields: Set[str] = set([ - "bar", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ReadOnlyFirst from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar"), - "baz": obj.get("baz") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_circular_all_of_ref.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_circular_all_of_ref.py index 854749b4fb13..1d59daedfa70 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_circular_all_of_ref.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_circular_all_of_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SecondCircularAllOfRef(BaseModel): """ @@ -37,61 +38,28 @@ class SecondCircularAllOfRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SecondCircularAllOfRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in circular_all_of_ref (list) - _items = [] - if self.circular_all_of_ref: - for _item_circular_all_of_ref in self.circular_all_of_ref: - if _item_circular_all_of_ref: - _items.append(_item_circular_all_of_ref.to_dict()) - _dict['circularAllOfRef'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SecondCircularAllOfRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name"), - "circularAllOfRef": [CircularAllOfRef.from_dict(_item) for _item in obj["circularAllOfRef"]] if obj.get("circularAllOfRef") is not None else None - }) - return _obj from petstore_api.models.circular_all_of_ref import CircularAllOfRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_ref.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_ref.py index c6627cf0ba63..68639c27be4e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_ref.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SecondRef(BaseModel): """ @@ -37,57 +38,28 @@ class SecondRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SecondRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of circular_ref - if self.circular_ref: - _dict['circular_ref'] = self.circular_ref.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SecondRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "circular_ref": CircularReferenceModel.from_dict(obj["circular_ref"]) if obj.get("circular_ref") is not None else None - }) - return _obj from petstore_api.models.circular_reference_model import CircularReferenceModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/self_reference_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/self_reference_model.py index 7c145db0d3ae..319aa1bbb7d7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/self_reference_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/self_reference_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SelfReferenceModel(BaseModel): """ @@ -37,57 +38,28 @@ class SelfReferenceModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SelfReferenceModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested - if self.nested: - _dict['nested'] = self.nested.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SelfReferenceModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested": DummyModel.from_dict(obj["nested"]) if obj.get("nested") is not None else None - }) - return _obj from petstore_api.models.dummy_model import DummyModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_model_name.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_model_name.py index 0336e24d17da..29712f6ce24e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_model_name.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_model_name.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SpecialModelName(BaseModel): """ @@ -36,52 +37,27 @@ class SpecialModelName(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SpecialModelName from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SpecialModelName from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "$special[property.name]": obj.get("$special[property.name]") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py index d3c8f6185683..36d84e99015d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.category import Category from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SpecialName(BaseModel): """ @@ -29,7 +30,10 @@ class SpecialName(BaseModel): """ # noqa: E501 var_property: Optional[StrictInt] = Field(default=None, alias="property") var_async: Optional[Category] = Field(default=None, alias="async") - var_schema: Optional[StrictStr] = Field(default=None, description="pet status in the store", alias="schema") + var_schema: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) __properties: ClassVar[List[str]] = ["property", "async", "schema"] @field_validator('var_schema') @@ -49,57 +53,27 @@ def var_schema_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SpecialName from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of var_async - if self.var_async: - _dict['async'] = self.var_async.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SpecialName from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "property": obj.get("property"), - "async": Category.from_dict(obj["async"]) if obj.get("async") is not None else None, - "schema": obj.get("schema") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tag.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tag.py index e5ddcbcd4a74..5b2c89ec90a6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tag.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tag.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tag(BaseModel): """ @@ -37,53 +38,27 @@ class Tag(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tag from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tag from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task.py index 312b2c8ee473..32fdaf499a98 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task.py @@ -22,7 +22,8 @@ from uuid import UUID from petstore_api.models.task_activity import TaskActivity from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Task(BaseModel): """ @@ -39,56 +40,27 @@ class Task(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Task from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of activity - if self.activity: - _dict['activity'] = self.activity.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Task from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "activity": TaskActivity.from_dict(obj["activity"]) if obj.get("activity") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py index cc1e1fc5a60f..39a1c0bbc375 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/task_activity.py @@ -20,132 +20,55 @@ from petstore_api.models.bathing import Bathing from petstore_api.models.feeding import Feeding from petstore_api.models.poop_cleaning import PoopCleaning -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] -class TaskActivity(BaseModel): +class TaskActivity(RootModel[Union[Bathing, Feeding, PoopCleaning]]): """ TaskActivity """ - # data type: PoopCleaning - oneof_schema_1_validator: Optional[PoopCleaning] = None - # data type: Feeding - oneof_schema_2_validator: Optional[Feeding] = None - # data type: Bathing - oneof_schema_3_validator: Optional[Bathing] = None - actual_instance: Optional[Union[Bathing, Feeding, PoopCleaning]] = None - one_of_schemas: Set[str] = { "Bathing", "Feeding", "PoopCleaning" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[Bathing, Feeding, PoopCleaning] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = TaskActivity.model_construct() - error_messages = [] - match = 0 - # validate data type: PoopCleaning - if not isinstance(v, PoopCleaning): - error_messages.append(f"Error! Input type `{type(v)}` is not `PoopCleaning`") - else: - match += 1 - # validate data type: Feeding - if not isinstance(v, Feeding): - error_messages.append(f"Error! Input type `{type(v)}` is not `Feeding`") - else: - match += 1 - # validate data type: Bathing - if not isinstance(v, Bathing): - error_messages.append(f"Error! Input type `{type(v)}` is not `Bathing`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into PoopCleaning - try: - instance.actual_instance = PoopCleaning.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into Feeding - try: - instance.actual_instance = Feeding.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into Bathing - try: - instance.actual_instance = Bathing.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py index cba4ab845e5e..f05c878e947d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestErrorResponsesWithModel400Response(BaseModel): """ @@ -36,52 +37,27 @@ class TestErrorResponsesWithModel400Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel400Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel400Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "reason400": obj.get("reason400") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py index 787ca11942ab..bf3e78f98b1e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestErrorResponsesWithModel404Response(BaseModel): """ @@ -36,52 +37,27 @@ class TestErrorResponsesWithModel404Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel404Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel404Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "reason404": obj.get("reason404") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_inline_freeform_additional_properties_request.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_inline_freeform_additional_properties_request.py index 7b93d84864f2..83309fd58987 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_inline_freeform_additional_properties_request.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_inline_freeform_additional_properties_request.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): """ @@ -37,64 +38,27 @@ class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "someProperty": obj.get("someProperty") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_model_with_enum_default.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_model_with_enum_default.py index 218fa8f16d22..4b19246316db 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_model_with_enum_default.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_model_with_enum_default.py @@ -22,7 +22,8 @@ from petstore_api.models.test_enum import TestEnum from petstore_api.models.test_enum_with_default import TestEnumWithDefault from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestModelWithEnumDefault(BaseModel): """ @@ -32,7 +33,10 @@ class TestModelWithEnumDefault(BaseModel): test_string: Optional[StrictStr] = None test_enum_with_default: Optional[TestEnumWithDefault] = TestEnumWithDefault.ZWEI test_string_with_default: Optional[StrictStr] = 'ahoy matey' - test_inline_defined_enum_with_default: Optional[StrictStr] = 'B' + test_inline_defined_enum_with_default: Optional[Literal['A', 'B', 'C']] = Field( + None, + description="test_inline_defined_enum_with_default of the TestModelWithEnumDefault" + ) __properties: ClassVar[List[str]] = ["test_enum", "test_string", "test_enum_with_default", "test_string_with_default", "test_inline_defined_enum_with_default"] @field_validator('test_inline_defined_enum_with_default') @@ -52,56 +56,27 @@ def test_inline_defined_enum_with_default_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestModelWithEnumDefault from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestModelWithEnumDefault from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "test_enum": obj.get("test_enum"), - "test_string": obj.get("test_string"), - "test_enum_with_default": obj.get("test_enum_with_default") if obj.get("test_enum_with_default") is not None else TestEnumWithDefault.ZWEI, - "test_string_with_default": obj.get("test_string_with_default") if obj.get("test_string_with_default") is not None else 'ahoy matey', - "test_inline_defined_enum_with_default": obj.get("test_inline_defined_enum_with_default") if obj.get("test_inline_defined_enum_with_default") is not None else 'B' - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_object_for_multipart_requests_request_marker.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_object_for_multipart_requests_request_marker.py index a5c3bfdbb1b5..c736089e90f7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_object_for_multipart_requests_request_marker.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_object_for_multipart_requests_request_marker.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestObjectForMultipartRequestsRequestMarker(BaseModel): """ @@ -36,52 +37,27 @@ class TestObjectForMultipartRequestsRequestMarker(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestObjectForMultipartRequestsRequestMarker from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestObjectForMultipartRequestsRequestMarker from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tiger.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tiger.py index bf8cbf0596ae..70b4af572ae1 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tiger.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tiger.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tiger(BaseModel): """ @@ -36,52 +37,27 @@ class Tiger(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tiger from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tiger from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "skill": obj.get("skill") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py index e50edf2efa85..4652d2ea4588 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UnnamedDictWithAdditionalModelListProperties(BaseModel): """ @@ -37,68 +38,27 @@ class UnnamedDictWithAdditionalModelListProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in dict_property (dict of array) - _field_dict_of_array = {} - if self.dict_property: - for _key_dict_property in self.dict_property: - if self.dict_property[_key_dict_property] is not None: - _field_dict_of_array[_key_dict_property] = [ - _item.to_dict() for _item in self.dict_property[_key_dict_property] - ] - _dict['dictProperty'] = _field_dict_of_array - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalModelListProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "dictProperty": dict( - (_k, - [CreatureInfo.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("dictProperty", {}).items() - ) - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py index 477dcae27c7c..57629cf53b18 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UnnamedDictWithAdditionalStringListProperties(BaseModel): """ @@ -36,52 +37,27 @@ class UnnamedDictWithAdditionalStringListProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalStringListProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "dictProperty": obj.get("dictProperty") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py index 9040618ac0d7..2cfefd30dad8 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): """ @@ -36,52 +37,27 @@ class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/user.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/user.py index 45e0a66f89dd..499f7f22d7a3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/user.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/user.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class User(BaseModel): """ @@ -43,59 +44,27 @@ class User(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of User from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of User from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "username": obj.get("username"), - "firstName": obj.get("firstName"), - "lastName": obj.get("lastName"), - "email": obj.get("email"), - "password": obj.get("password"), - "phone": obj.get("phone"), - "userStatus": obj.get("userStatus") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/with_nested_one_of.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/with_nested_one_of.py index f2cd8b7a3a30..2358231b1f89 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/with_nested_one_of.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/with_nested_one_of.py @@ -22,7 +22,8 @@ from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.pig import Pig from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class WithNestedOneOf(BaseModel): """ @@ -40,57 +41,27 @@ class WithNestedOneOf(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of WithNestedOneOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested_pig - if self.nested_pig: - _dict['nested_pig'] = self.nested_pig.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of WithNestedOneOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested_pig": Pig.from_dict(obj["nested_pig"]) if obj.get("nested_pig") is not None else None, - "nested_oneof_enum_string": obj.get("nested_oneof_enum_string") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesAnyType.md b/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesAnyType.md index 314cba3a614c..b94c1e6d7d19 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesAnyType.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesAnyType.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_any_type import AdditionalPropert # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesAnyType from a JSON string -additional_properties_any_type_instance = AdditionalPropertiesAnyType.from_json(json) +additional_properties_any_type_instance = AdditionalPropertiesAnyType.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesAnyType.to_json()) +print(additional_properties_any_type_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_any_type_dict = additional_properties_any_type_instance.to_dict() +additional_properties_any_type_dict = additional_properties_any_type_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesAnyType from a dict -additional_properties_any_type_from_dict = AdditionalPropertiesAnyType.from_dict(additional_properties_any_type_dict) +additional_properties_any_type_from_dict = AdditionalPropertiesAnyType.model_validate(additional_properties_any_type_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesClass.md index 8d4c08707f55..4c880d6853e8 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesClass.md @@ -16,14 +16,14 @@ from petstore_api.models.additional_properties_class import AdditionalProperties # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesClass from a JSON string -additional_properties_class_instance = AdditionalPropertiesClass.from_json(json) +additional_properties_class_instance = AdditionalPropertiesClass.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesClass.to_json()) +print(additional_properties_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_class_dict = additional_properties_class_instance.to_dict() +additional_properties_class_dict = additional_properties_class_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesClass from a dict -additional_properties_class_from_dict = AdditionalPropertiesClass.from_dict(additional_properties_class_dict) +additional_properties_class_from_dict = AdditionalPropertiesClass.model_validate(additional_properties_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesObject.md b/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesObject.md index d647ec64896f..bf6743709338 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesObject.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesObject.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_object import AdditionalPropertie # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesObject from a JSON string -additional_properties_object_instance = AdditionalPropertiesObject.from_json(json) +additional_properties_object_instance = AdditionalPropertiesObject.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesObject.to_json()) +print(additional_properties_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_object_dict = additional_properties_object_instance.to_dict() +additional_properties_object_dict = additional_properties_object_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesObject from a dict -additional_properties_object_from_dict = AdditionalPropertiesObject.from_dict(additional_properties_object_dict) +additional_properties_object_from_dict = AdditionalPropertiesObject.model_validate(additional_properties_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesWithDescriptionOnly.md b/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesWithDescriptionOnly.md index 061f5524872b..1cb2a02f7584 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesWithDescriptionOnly.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/AdditionalPropertiesWithDescriptionOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_with_description_only import Addi # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string -additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.from_json(json) +additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesWithDescriptionOnly.to_json()) +print(additional_properties_with_description_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.to_dict() +additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesWithDescriptionOnly from a dict -additional_properties_with_description_only_from_dict = AdditionalPropertiesWithDescriptionOnly.from_dict(additional_properties_with_description_only_dict) +additional_properties_with_description_only_from_dict = AdditionalPropertiesWithDescriptionOnly.model_validate(additional_properties_with_description_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/AllOfSuperModel.md b/samples/openapi3/client/petstore/python-httpx/docs/AllOfSuperModel.md index 421a1527f1ef..88cb95097517 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/AllOfSuperModel.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/AllOfSuperModel.md @@ -15,14 +15,14 @@ from petstore_api.models.all_of_super_model import AllOfSuperModel # TODO update the JSON string below json = "{}" # create an instance of AllOfSuperModel from a JSON string -all_of_super_model_instance = AllOfSuperModel.from_json(json) +all_of_super_model_instance = AllOfSuperModel.model_validate_json(json) # print the JSON string representation of the object -print(AllOfSuperModel.to_json()) +print(all_of_super_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -all_of_super_model_dict = all_of_super_model_instance.to_dict() +all_of_super_model_dict = all_of_super_model_instance.model_dump(by_alias=True) # create an instance of AllOfSuperModel from a dict -all_of_super_model_from_dict = AllOfSuperModel.from_dict(all_of_super_model_dict) +all_of_super_model_from_dict = AllOfSuperModel.model_validate(all_of_super_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/AllOfWithSingleRef.md b/samples/openapi3/client/petstore/python-httpx/docs/AllOfWithSingleRef.md index 203a4b5da3d5..dd0f755dfe65 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/AllOfWithSingleRef.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/AllOfWithSingleRef.md @@ -16,14 +16,14 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef # TODO update the JSON string below json = "{}" # create an instance of AllOfWithSingleRef from a JSON string -all_of_with_single_ref_instance = AllOfWithSingleRef.from_json(json) +all_of_with_single_ref_instance = AllOfWithSingleRef.model_validate_json(json) # print the JSON string representation of the object -print(AllOfWithSingleRef.to_json()) +print(all_of_with_single_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -all_of_with_single_ref_dict = all_of_with_single_ref_instance.to_dict() +all_of_with_single_ref_dict = all_of_with_single_ref_instance.model_dump(by_alias=True) # create an instance of AllOfWithSingleRef from a dict -all_of_with_single_ref_from_dict = AllOfWithSingleRef.from_dict(all_of_with_single_ref_dict) +all_of_with_single_ref_from_dict = AllOfWithSingleRef.model_validate(all_of_with_single_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Animal.md b/samples/openapi3/client/petstore/python-httpx/docs/Animal.md index 381d27b66e44..fcded75f52be 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Animal.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Animal.md @@ -16,14 +16,14 @@ from petstore_api.models.animal import Animal # TODO update the JSON string below json = "{}" # create an instance of Animal from a JSON string -animal_instance = Animal.from_json(json) +animal_instance = Animal.model_validate_json(json) # print the JSON string representation of the object -print(Animal.to_json()) +print(animal_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -animal_dict = animal_instance.to_dict() +animal_dict = animal_instance.model_dump(by_alias=True) # create an instance of Animal from a dict -animal_from_dict = Animal.from_dict(animal_dict) +animal_from_dict = Animal.model_validate(animal_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/AnyOfColor.md b/samples/openapi3/client/petstore/python-httpx/docs/AnyOfColor.md index 6ed75dd7b48a..02aab883b2b0 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/AnyOfColor.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/AnyOfColor.md @@ -15,14 +15,14 @@ from petstore_api.models.any_of_color import AnyOfColor # TODO update the JSON string below json = "{}" # create an instance of AnyOfColor from a JSON string -any_of_color_instance = AnyOfColor.from_json(json) +any_of_color_instance = AnyOfColor.model_validate_json(json) # print the JSON string representation of the object -print(AnyOfColor.to_json()) +print(any_of_color_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -any_of_color_dict = any_of_color_instance.to_dict() +any_of_color_dict = any_of_color_instance.model_dump(by_alias=True) # create an instance of AnyOfColor from a dict -any_of_color_from_dict = AnyOfColor.from_dict(any_of_color_dict) +any_of_color_from_dict = AnyOfColor.model_validate(any_of_color_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/AnyOfPig.md b/samples/openapi3/client/petstore/python-httpx/docs/AnyOfPig.md index 9367e2261898..db2878121f29 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/AnyOfPig.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/AnyOfPig.md @@ -17,14 +17,14 @@ from petstore_api.models.any_of_pig import AnyOfPig # TODO update the JSON string below json = "{}" # create an instance of AnyOfPig from a JSON string -any_of_pig_instance = AnyOfPig.from_json(json) +any_of_pig_instance = AnyOfPig.model_validate_json(json) # print the JSON string representation of the object -print(AnyOfPig.to_json()) +print(any_of_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -any_of_pig_dict = any_of_pig_instance.to_dict() +any_of_pig_dict = any_of_pig_instance.model_dump(by_alias=True) # create an instance of AnyOfPig from a dict -any_of_pig_from_dict = AnyOfPig.from_dict(any_of_pig_dict) +any_of_pig_from_dict = AnyOfPig.model_validate(any_of_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfArrayOfModel.md b/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfArrayOfModel.md index f866863d53f9..e8274d8fbb52 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfArrayOfModel.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel # TODO update the JSON string below json = "{}" # create an instance of ArrayOfArrayOfModel from a JSON string -array_of_array_of_model_instance = ArrayOfArrayOfModel.from_json(json) +array_of_array_of_model_instance = ArrayOfArrayOfModel.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfArrayOfModel.to_json()) +print(array_of_array_of_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_array_of_model_dict = array_of_array_of_model_instance.to_dict() +array_of_array_of_model_dict = array_of_array_of_model_instance.model_dump(by_alias=True) # create an instance of ArrayOfArrayOfModel from a dict -array_of_array_of_model_from_dict = ArrayOfArrayOfModel.from_dict(array_of_array_of_model_dict) +array_of_array_of_model_from_dict = ArrayOfArrayOfModel.model_validate(array_of_array_of_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfArrayOfNumberOnly.md index 32bd2dfbf1e2..8931a1c7e467 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfArrayOfNumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumb # TODO update the JSON string below json = "{}" # create an instance of ArrayOfArrayOfNumberOnly from a JSON string -array_of_array_of_number_only_instance = ArrayOfArrayOfNumberOnly.from_json(json) +array_of_array_of_number_only_instance = ArrayOfArrayOfNumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfArrayOfNumberOnly.to_json()) +print(array_of_array_of_number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_array_of_number_only_dict = array_of_array_of_number_only_instance.to_dict() +array_of_array_of_number_only_dict = array_of_array_of_number_only_instance.model_dump(by_alias=True) # create an instance of ArrayOfArrayOfNumberOnly from a dict -array_of_array_of_number_only_from_dict = ArrayOfArrayOfNumberOnly.from_dict(array_of_array_of_number_only_dict) +array_of_array_of_number_only_from_dict = ArrayOfArrayOfNumberOnly.model_validate(array_of_array_of_number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfNumberOnly.md index b814d7594942..a709583be699 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ArrayOfNumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly # TODO update the JSON string below json = "{}" # create an instance of ArrayOfNumberOnly from a JSON string -array_of_number_only_instance = ArrayOfNumberOnly.from_json(json) +array_of_number_only_instance = ArrayOfNumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfNumberOnly.to_json()) +print(array_of_number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_number_only_dict = array_of_number_only_instance.to_dict() +array_of_number_only_dict = array_of_number_only_instance.model_dump(by_alias=True) # create an instance of ArrayOfNumberOnly from a dict -array_of_number_only_from_dict = ArrayOfNumberOnly.from_dict(array_of_number_only_dict) +array_of_number_only_from_dict = ArrayOfNumberOnly.model_validate(array_of_number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ArrayTest.md b/samples/openapi3/client/petstore/python-httpx/docs/ArrayTest.md index ed871fae662d..a99eb056c5ca 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ArrayTest.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ArrayTest.md @@ -18,14 +18,14 @@ from petstore_api.models.array_test import ArrayTest # TODO update the JSON string below json = "{}" # create an instance of ArrayTest from a JSON string -array_test_instance = ArrayTest.from_json(json) +array_test_instance = ArrayTest.model_validate_json(json) # print the JSON string representation of the object -print(ArrayTest.to_json()) +print(array_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_test_dict = array_test_instance.to_dict() +array_test_dict = array_test_instance.model_dump(by_alias=True) # create an instance of ArrayTest from a dict -array_test_from_dict = ArrayTest.from_dict(array_test_dict) +array_test_from_dict = ArrayTest.model_validate(array_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/BaseDiscriminator.md b/samples/openapi3/client/petstore/python-httpx/docs/BaseDiscriminator.md index fcdbeb032e68..0482396cbcf8 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/BaseDiscriminator.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/BaseDiscriminator.md @@ -15,14 +15,14 @@ from petstore_api.models.base_discriminator import BaseDiscriminator # TODO update the JSON string below json = "{}" # create an instance of BaseDiscriminator from a JSON string -base_discriminator_instance = BaseDiscriminator.from_json(json) +base_discriminator_instance = BaseDiscriminator.model_validate_json(json) # print the JSON string representation of the object -print(BaseDiscriminator.to_json()) +print(base_discriminator_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -base_discriminator_dict = base_discriminator_instance.to_dict() +base_discriminator_dict = base_discriminator_instance.model_dump(by_alias=True) # create an instance of BaseDiscriminator from a dict -base_discriminator_from_dict = BaseDiscriminator.from_dict(base_discriminator_dict) +base_discriminator_from_dict = BaseDiscriminator.model_validate(base_discriminator_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/BasquePig.md b/samples/openapi3/client/petstore/python-httpx/docs/BasquePig.md index ee28d628722f..9844d05b3740 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/BasquePig.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/BasquePig.md @@ -16,14 +16,14 @@ from petstore_api.models.basque_pig import BasquePig # TODO update the JSON string below json = "{}" # create an instance of BasquePig from a JSON string -basque_pig_instance = BasquePig.from_json(json) +basque_pig_instance = BasquePig.model_validate_json(json) # print the JSON string representation of the object -print(BasquePig.to_json()) +print(basque_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -basque_pig_dict = basque_pig_instance.to_dict() +basque_pig_dict = basque_pig_instance.model_dump(by_alias=True) # create an instance of BasquePig from a dict -basque_pig_from_dict = BasquePig.from_dict(basque_pig_dict) +basque_pig_from_dict = BasquePig.model_validate(basque_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Bathing.md b/samples/openapi3/client/petstore/python-httpx/docs/Bathing.md index 6ad70e2f67cc..2c8d8332629b 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Bathing.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Bathing.md @@ -17,14 +17,14 @@ from petstore_api.models.bathing import Bathing # TODO update the JSON string below json = "{}" # create an instance of Bathing from a JSON string -bathing_instance = Bathing.from_json(json) +bathing_instance = Bathing.model_validate_json(json) # print the JSON string representation of the object -print(Bathing.to_json()) +print(bathing_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -bathing_dict = bathing_instance.to_dict() +bathing_dict = bathing_instance.model_dump(by_alias=True) # create an instance of Bathing from a dict -bathing_from_dict = Bathing.from_dict(bathing_dict) +bathing_from_dict = Bathing.model_validate(bathing_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Capitalization.md b/samples/openapi3/client/petstore/python-httpx/docs/Capitalization.md index 6f564a8ed8c9..55fcc0c01cb2 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Capitalization.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Capitalization.md @@ -20,14 +20,14 @@ from petstore_api.models.capitalization import Capitalization # TODO update the JSON string below json = "{}" # create an instance of Capitalization from a JSON string -capitalization_instance = Capitalization.from_json(json) +capitalization_instance = Capitalization.model_validate_json(json) # print the JSON string representation of the object -print(Capitalization.to_json()) +print(capitalization_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -capitalization_dict = capitalization_instance.to_dict() +capitalization_dict = capitalization_instance.model_dump(by_alias=True) # create an instance of Capitalization from a dict -capitalization_from_dict = Capitalization.from_dict(capitalization_dict) +capitalization_from_dict = Capitalization.model_validate(capitalization_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Cat.md b/samples/openapi3/client/petstore/python-httpx/docs/Cat.md index d0e39efdb33e..0845d68bd487 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Cat.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Cat.md @@ -15,14 +15,14 @@ from petstore_api.models.cat import Cat # TODO update the JSON string below json = "{}" # create an instance of Cat from a JSON string -cat_instance = Cat.from_json(json) +cat_instance = Cat.model_validate_json(json) # print the JSON string representation of the object -print(Cat.to_json()) +print(cat_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -cat_dict = cat_instance.to_dict() +cat_dict = cat_instance.model_dump(by_alias=True) # create an instance of Cat from a dict -cat_from_dict = Cat.from_dict(cat_dict) +cat_from_dict = Cat.model_validate(cat_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Category.md b/samples/openapi3/client/petstore/python-httpx/docs/Category.md index dbde14b7344c..8a14791c7925 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Category.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Category.md @@ -16,14 +16,14 @@ from petstore_api.models.category import Category # TODO update the JSON string below json = "{}" # create an instance of Category from a JSON string -category_instance = Category.from_json(json) +category_instance = Category.model_validate_json(json) # print the JSON string representation of the object -print(Category.to_json()) +print(category_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -category_dict = category_instance.to_dict() +category_dict = category_instance.model_dump(by_alias=True) # create an instance of Category from a dict -category_from_dict = Category.from_dict(category_dict) +category_from_dict = Category.model_validate(category_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/CircularAllOfRef.md b/samples/openapi3/client/petstore/python-httpx/docs/CircularAllOfRef.md index 65b171177e58..f937a53cfe3c 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/CircularAllOfRef.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/CircularAllOfRef.md @@ -16,14 +16,14 @@ from petstore_api.models.circular_all_of_ref import CircularAllOfRef # TODO update the JSON string below json = "{}" # create an instance of CircularAllOfRef from a JSON string -circular_all_of_ref_instance = CircularAllOfRef.from_json(json) +circular_all_of_ref_instance = CircularAllOfRef.model_validate_json(json) # print the JSON string representation of the object -print(CircularAllOfRef.to_json()) +print(circular_all_of_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -circular_all_of_ref_dict = circular_all_of_ref_instance.to_dict() +circular_all_of_ref_dict = circular_all_of_ref_instance.model_dump(by_alias=True) # create an instance of CircularAllOfRef from a dict -circular_all_of_ref_from_dict = CircularAllOfRef.from_dict(circular_all_of_ref_dict) +circular_all_of_ref_from_dict = CircularAllOfRef.model_validate(circular_all_of_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/CircularReferenceModel.md b/samples/openapi3/client/petstore/python-httpx/docs/CircularReferenceModel.md index 87216f7273ab..9a39f46e5d7d 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/CircularReferenceModel.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/CircularReferenceModel.md @@ -16,14 +16,14 @@ from petstore_api.models.circular_reference_model import CircularReferenceModel # TODO update the JSON string below json = "{}" # create an instance of CircularReferenceModel from a JSON string -circular_reference_model_instance = CircularReferenceModel.from_json(json) +circular_reference_model_instance = CircularReferenceModel.model_validate_json(json) # print the JSON string representation of the object -print(CircularReferenceModel.to_json()) +print(circular_reference_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -circular_reference_model_dict = circular_reference_model_instance.to_dict() +circular_reference_model_dict = circular_reference_model_instance.model_dump(by_alias=True) # create an instance of CircularReferenceModel from a dict -circular_reference_model_from_dict = CircularReferenceModel.from_dict(circular_reference_model_dict) +circular_reference_model_from_dict = CircularReferenceModel.model_validate(circular_reference_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ClassModel.md b/samples/openapi3/client/petstore/python-httpx/docs/ClassModel.md index ea76a5c157bf..50fbfefa7661 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ClassModel.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ClassModel.md @@ -16,14 +16,14 @@ from petstore_api.models.class_model import ClassModel # TODO update the JSON string below json = "{}" # create an instance of ClassModel from a JSON string -class_model_instance = ClassModel.from_json(json) +class_model_instance = ClassModel.model_validate_json(json) # print the JSON string representation of the object -print(ClassModel.to_json()) +print(class_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -class_model_dict = class_model_instance.to_dict() +class_model_dict = class_model_instance.model_dump(by_alias=True) # create an instance of ClassModel from a dict -class_model_from_dict = ClassModel.from_dict(class_model_dict) +class_model_from_dict = ClassModel.model_validate(class_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Client.md b/samples/openapi3/client/petstore/python-httpx/docs/Client.md index 22321c189150..160a80da457f 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Client.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Client.md @@ -15,14 +15,14 @@ from petstore_api.models.client import Client # TODO update the JSON string below json = "{}" # create an instance of Client from a JSON string -client_instance = Client.from_json(json) +client_instance = Client.model_validate_json(json) # print the JSON string representation of the object -print(Client.to_json()) +print(client_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -client_dict = client_instance.to_dict() +client_dict = client_instance.model_dump(by_alias=True) # create an instance of Client from a dict -client_from_dict = Client.from_dict(client_dict) +client_from_dict = Client.model_validate(client_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Color.md b/samples/openapi3/client/petstore/python-httpx/docs/Color.md index 9ac3ab2e91f4..1425ff185040 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Color.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Color.md @@ -15,14 +15,14 @@ from petstore_api.models.color import Color # TODO update the JSON string below json = "{}" # create an instance of Color from a JSON string -color_instance = Color.from_json(json) +color_instance = Color.model_validate_json(json) # print the JSON string representation of the object -print(Color.to_json()) +print(color_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -color_dict = color_instance.to_dict() +color_dict = color_instance.model_dump(by_alias=True) # create an instance of Color from a dict -color_from_dict = Color.from_dict(color_dict) +color_from_dict = Color.model_validate(color_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Creature.md b/samples/openapi3/client/petstore/python-httpx/docs/Creature.md index a4710214c198..eb0ba3b2f127 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Creature.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Creature.md @@ -16,14 +16,14 @@ from petstore_api.models.creature import Creature # TODO update the JSON string below json = "{}" # create an instance of Creature from a JSON string -creature_instance = Creature.from_json(json) +creature_instance = Creature.model_validate_json(json) # print the JSON string representation of the object -print(Creature.to_json()) +print(creature_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -creature_dict = creature_instance.to_dict() +creature_dict = creature_instance.model_dump(by_alias=True) # create an instance of Creature from a dict -creature_from_dict = Creature.from_dict(creature_dict) +creature_from_dict = Creature.model_validate(creature_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/CreatureInfo.md b/samples/openapi3/client/petstore/python-httpx/docs/CreatureInfo.md index db3b82bb9ff5..156d93939201 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/CreatureInfo.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/CreatureInfo.md @@ -15,14 +15,14 @@ from petstore_api.models.creature_info import CreatureInfo # TODO update the JSON string below json = "{}" # create an instance of CreatureInfo from a JSON string -creature_info_instance = CreatureInfo.from_json(json) +creature_info_instance = CreatureInfo.model_validate_json(json) # print the JSON string representation of the object -print(CreatureInfo.to_json()) +print(creature_info_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -creature_info_dict = creature_info_instance.to_dict() +creature_info_dict = creature_info_instance.model_dump(by_alias=True) # create an instance of CreatureInfo from a dict -creature_info_from_dict = CreatureInfo.from_dict(creature_info_dict) +creature_info_from_dict = CreatureInfo.model_validate(creature_info_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/DanishPig.md b/samples/openapi3/client/petstore/python-httpx/docs/DanishPig.md index 16941388832a..5eac27f79e79 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/DanishPig.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/DanishPig.md @@ -16,14 +16,14 @@ from petstore_api.models.danish_pig import DanishPig # TODO update the JSON string below json = "{}" # create an instance of DanishPig from a JSON string -danish_pig_instance = DanishPig.from_json(json) +danish_pig_instance = DanishPig.model_validate_json(json) # print the JSON string representation of the object -print(DanishPig.to_json()) +print(danish_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -danish_pig_dict = danish_pig_instance.to_dict() +danish_pig_dict = danish_pig_instance.model_dump(by_alias=True) # create an instance of DanishPig from a dict -danish_pig_from_dict = DanishPig.from_dict(danish_pig_dict) +danish_pig_from_dict = DanishPig.model_validate(danish_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/DeprecatedObject.md b/samples/openapi3/client/petstore/python-httpx/docs/DeprecatedObject.md index 6b362f379ba4..ff3aa9812e2d 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/DeprecatedObject.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/DeprecatedObject.md @@ -15,14 +15,14 @@ from petstore_api.models.deprecated_object import DeprecatedObject # TODO update the JSON string below json = "{}" # create an instance of DeprecatedObject from a JSON string -deprecated_object_instance = DeprecatedObject.from_json(json) +deprecated_object_instance = DeprecatedObject.model_validate_json(json) # print the JSON string representation of the object -print(DeprecatedObject.to_json()) +print(deprecated_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -deprecated_object_dict = deprecated_object_instance.to_dict() +deprecated_object_dict = deprecated_object_instance.model_dump(by_alias=True) # create an instance of DeprecatedObject from a dict -deprecated_object_from_dict = DeprecatedObject.from_dict(deprecated_object_dict) +deprecated_object_from_dict = DeprecatedObject.model_validate(deprecated_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/DiscriminatorAllOfSub.md b/samples/openapi3/client/petstore/python-httpx/docs/DiscriminatorAllOfSub.md index f72b6e8e68ca..aa7af45b99fa 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/DiscriminatorAllOfSub.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/DiscriminatorAllOfSub.md @@ -14,14 +14,14 @@ from petstore_api.models.discriminator_all_of_sub import DiscriminatorAllOfSub # TODO update the JSON string below json = "{}" # create an instance of DiscriminatorAllOfSub from a JSON string -discriminator_all_of_sub_instance = DiscriminatorAllOfSub.from_json(json) +discriminator_all_of_sub_instance = DiscriminatorAllOfSub.model_validate_json(json) # print the JSON string representation of the object -print(DiscriminatorAllOfSub.to_json()) +print(discriminator_all_of_sub_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -discriminator_all_of_sub_dict = discriminator_all_of_sub_instance.to_dict() +discriminator_all_of_sub_dict = discriminator_all_of_sub_instance.model_dump(by_alias=True) # create an instance of DiscriminatorAllOfSub from a dict -discriminator_all_of_sub_from_dict = DiscriminatorAllOfSub.from_dict(discriminator_all_of_sub_dict) +discriminator_all_of_sub_from_dict = DiscriminatorAllOfSub.model_validate(discriminator_all_of_sub_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/DiscriminatorAllOfSuper.md b/samples/openapi3/client/petstore/python-httpx/docs/DiscriminatorAllOfSuper.md index 477c05bfc446..c21e5b2296ac 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/DiscriminatorAllOfSuper.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/DiscriminatorAllOfSuper.md @@ -15,14 +15,14 @@ from petstore_api.models.discriminator_all_of_super import DiscriminatorAllOfSup # TODO update the JSON string below json = "{}" # create an instance of DiscriminatorAllOfSuper from a JSON string -discriminator_all_of_super_instance = DiscriminatorAllOfSuper.from_json(json) +discriminator_all_of_super_instance = DiscriminatorAllOfSuper.model_validate_json(json) # print the JSON string representation of the object -print(DiscriminatorAllOfSuper.to_json()) +print(discriminator_all_of_super_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -discriminator_all_of_super_dict = discriminator_all_of_super_instance.to_dict() +discriminator_all_of_super_dict = discriminator_all_of_super_instance.model_dump(by_alias=True) # create an instance of DiscriminatorAllOfSuper from a dict -discriminator_all_of_super_from_dict = DiscriminatorAllOfSuper.from_dict(discriminator_all_of_super_dict) +discriminator_all_of_super_from_dict = DiscriminatorAllOfSuper.model_validate(discriminator_all_of_super_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Dog.md b/samples/openapi3/client/petstore/python-httpx/docs/Dog.md index ed23f613d01d..2065d42f5f6b 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Dog.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Dog.md @@ -15,14 +15,14 @@ from petstore_api.models.dog import Dog # TODO update the JSON string below json = "{}" # create an instance of Dog from a JSON string -dog_instance = Dog.from_json(json) +dog_instance = Dog.model_validate_json(json) # print the JSON string representation of the object -print(Dog.to_json()) +print(dog_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -dog_dict = dog_instance.to_dict() +dog_dict = dog_instance.model_dump(by_alias=True) # create an instance of Dog from a dict -dog_from_dict = Dog.from_dict(dog_dict) +dog_from_dict = Dog.model_validate(dog_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/DummyModel.md b/samples/openapi3/client/petstore/python-httpx/docs/DummyModel.md index 01b675977f58..dfe28d9f75b1 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/DummyModel.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/DummyModel.md @@ -16,14 +16,14 @@ from petstore_api.models.dummy_model import DummyModel # TODO update the JSON string below json = "{}" # create an instance of DummyModel from a JSON string -dummy_model_instance = DummyModel.from_json(json) +dummy_model_instance = DummyModel.model_validate_json(json) # print the JSON string representation of the object -print(DummyModel.to_json()) +print(dummy_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -dummy_model_dict = dummy_model_instance.to_dict() +dummy_model_dict = dummy_model_instance.model_dump(by_alias=True) # create an instance of DummyModel from a dict -dummy_model_from_dict = DummyModel.from_dict(dummy_model_dict) +dummy_model_from_dict = DummyModel.model_validate(dummy_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/EnumArrays.md b/samples/openapi3/client/petstore/python-httpx/docs/EnumArrays.md index f44617497bce..bf8b1a6cd05c 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/EnumArrays.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/EnumArrays.md @@ -16,14 +16,14 @@ from petstore_api.models.enum_arrays import EnumArrays # TODO update the JSON string below json = "{}" # create an instance of EnumArrays from a JSON string -enum_arrays_instance = EnumArrays.from_json(json) +enum_arrays_instance = EnumArrays.model_validate_json(json) # print the JSON string representation of the object -print(EnumArrays.to_json()) +print(enum_arrays_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_arrays_dict = enum_arrays_instance.to_dict() +enum_arrays_dict = enum_arrays_instance.model_dump(by_alias=True) # create an instance of EnumArrays from a dict -enum_arrays_from_dict = EnumArrays.from_dict(enum_arrays_dict) +enum_arrays_from_dict = EnumArrays.model_validate(enum_arrays_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/EnumRefWithDefaultValue.md b/samples/openapi3/client/petstore/python-httpx/docs/EnumRefWithDefaultValue.md index eeb0dc66969f..cbe6845479eb 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/EnumRefWithDefaultValue.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/EnumRefWithDefaultValue.md @@ -15,14 +15,14 @@ from petstore_api.models.enum_ref_with_default_value import EnumRefWithDefaultVa # TODO update the JSON string below json = "{}" # create an instance of EnumRefWithDefaultValue from a JSON string -enum_ref_with_default_value_instance = EnumRefWithDefaultValue.from_json(json) +enum_ref_with_default_value_instance = EnumRefWithDefaultValue.model_validate_json(json) # print the JSON string representation of the object -print(EnumRefWithDefaultValue.to_json()) +print(enum_ref_with_default_value_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_ref_with_default_value_dict = enum_ref_with_default_value_instance.to_dict() +enum_ref_with_default_value_dict = enum_ref_with_default_value_instance.model_dump(by_alias=True) # create an instance of EnumRefWithDefaultValue from a dict -enum_ref_with_default_value_from_dict = EnumRefWithDefaultValue.from_dict(enum_ref_with_default_value_dict) +enum_ref_with_default_value_from_dict = EnumRefWithDefaultValue.model_validate(enum_ref_with_default_value_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/EnumTest.md b/samples/openapi3/client/petstore/python-httpx/docs/EnumTest.md index 9f96c605d888..6ce4891aa9d5 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/EnumTest.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/EnumTest.md @@ -27,14 +27,14 @@ from petstore_api.models.enum_test import EnumTest # TODO update the JSON string below json = "{}" # create an instance of EnumTest from a JSON string -enum_test_instance = EnumTest.from_json(json) +enum_test_instance = EnumTest.model_validate_json(json) # print the JSON string representation of the object -print(EnumTest.to_json()) +print(enum_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_test_dict = enum_test_instance.to_dict() +enum_test_dict = enum_test_instance.model_dump(by_alias=True) # create an instance of EnumTest from a dict -enum_test_from_dict = EnumTest.from_dict(enum_test_dict) +enum_test_from_dict = EnumTest.model_validate(enum_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Feeding.md b/samples/openapi3/client/petstore/python-httpx/docs/Feeding.md index 9f92b5d964d3..773d1373cca0 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Feeding.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Feeding.md @@ -17,14 +17,14 @@ from petstore_api.models.feeding import Feeding # TODO update the JSON string below json = "{}" # create an instance of Feeding from a JSON string -feeding_instance = Feeding.from_json(json) +feeding_instance = Feeding.model_validate_json(json) # print the JSON string representation of the object -print(Feeding.to_json()) +print(feeding_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -feeding_dict = feeding_instance.to_dict() +feeding_dict = feeding_instance.model_dump(by_alias=True) # create an instance of Feeding from a dict -feeding_from_dict = Feeding.from_dict(feeding_dict) +feeding_from_dict = Feeding.model_validate(feeding_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/File.md b/samples/openapi3/client/petstore/python-httpx/docs/File.md index 23f0567411ce..3fe748f4f30f 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/File.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/File.md @@ -16,14 +16,14 @@ from petstore_api.models.file import File # TODO update the JSON string below json = "{}" # create an instance of File from a JSON string -file_instance = File.from_json(json) +file_instance = File.model_validate_json(json) # print the JSON string representation of the object -print(File.to_json()) +print(file_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -file_dict = file_instance.to_dict() +file_dict = file_instance.model_dump(by_alias=True) # create an instance of File from a dict -file_from_dict = File.from_dict(file_dict) +file_from_dict = File.model_validate(file_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python-httpx/docs/FileSchemaTestClass.md index e1118042a8ec..78bc4ae135da 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/FileSchemaTestClass.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/FileSchemaTestClass.md @@ -16,14 +16,14 @@ from petstore_api.models.file_schema_test_class import FileSchemaTestClass # TODO update the JSON string below json = "{}" # create an instance of FileSchemaTestClass from a JSON string -file_schema_test_class_instance = FileSchemaTestClass.from_json(json) +file_schema_test_class_instance = FileSchemaTestClass.model_validate_json(json) # print the JSON string representation of the object -print(FileSchemaTestClass.to_json()) +print(file_schema_test_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -file_schema_test_class_dict = file_schema_test_class_instance.to_dict() +file_schema_test_class_dict = file_schema_test_class_instance.model_dump(by_alias=True) # create an instance of FileSchemaTestClass from a dict -file_schema_test_class_from_dict = FileSchemaTestClass.from_dict(file_schema_test_class_dict) +file_schema_test_class_from_dict = FileSchemaTestClass.model_validate(file_schema_test_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/FirstRef.md b/samples/openapi3/client/petstore/python-httpx/docs/FirstRef.md index 94b8ddc5ac22..6da6650e5df7 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/FirstRef.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/FirstRef.md @@ -16,14 +16,14 @@ from petstore_api.models.first_ref import FirstRef # TODO update the JSON string below json = "{}" # create an instance of FirstRef from a JSON string -first_ref_instance = FirstRef.from_json(json) +first_ref_instance = FirstRef.model_validate_json(json) # print the JSON string representation of the object -print(FirstRef.to_json()) +print(first_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -first_ref_dict = first_ref_instance.to_dict() +first_ref_dict = first_ref_instance.model_dump(by_alias=True) # create an instance of FirstRef from a dict -first_ref_from_dict = FirstRef.from_dict(first_ref_dict) +first_ref_from_dict = FirstRef.model_validate(first_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Foo.md b/samples/openapi3/client/petstore/python-httpx/docs/Foo.md index f635b0daa6db..c11ae111ee22 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Foo.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Foo.md @@ -15,14 +15,14 @@ from petstore_api.models.foo import Foo # TODO update the JSON string below json = "{}" # create an instance of Foo from a JSON string -foo_instance = Foo.from_json(json) +foo_instance = Foo.model_validate_json(json) # print the JSON string representation of the object -print(Foo.to_json()) +print(foo_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -foo_dict = foo_instance.to_dict() +foo_dict = foo_instance.model_dump(by_alias=True) # create an instance of Foo from a dict -foo_from_dict = Foo.from_dict(foo_dict) +foo_from_dict = Foo.model_validate(foo_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/FooGetDefaultResponse.md b/samples/openapi3/client/petstore/python-httpx/docs/FooGetDefaultResponse.md index 8d84f795b00a..aaccf08bfd2e 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/FooGetDefaultResponse.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/FooGetDefaultResponse.md @@ -15,14 +15,14 @@ from petstore_api.models.foo_get_default_response import FooGetDefaultResponse # TODO update the JSON string below json = "{}" # create an instance of FooGetDefaultResponse from a JSON string -foo_get_default_response_instance = FooGetDefaultResponse.from_json(json) +foo_get_default_response_instance = FooGetDefaultResponse.model_validate_json(json) # print the JSON string representation of the object -print(FooGetDefaultResponse.to_json()) +print(foo_get_default_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -foo_get_default_response_dict = foo_get_default_response_instance.to_dict() +foo_get_default_response_dict = foo_get_default_response_instance.model_dump(by_alias=True) # create an instance of FooGetDefaultResponse from a dict -foo_get_default_response_from_dict = FooGetDefaultResponse.from_dict(foo_get_default_response_dict) +foo_get_default_response_from_dict = FooGetDefaultResponse.model_validate(foo_get_default_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/FormatTest.md b/samples/openapi3/client/petstore/python-httpx/docs/FormatTest.md index 714d2401bbae..98c3dc89570d 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/FormatTest.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/FormatTest.md @@ -31,14 +31,14 @@ from petstore_api.models.format_test import FormatTest # TODO update the JSON string below json = "{}" # create an instance of FormatTest from a JSON string -format_test_instance = FormatTest.from_json(json) +format_test_instance = FormatTest.model_validate_json(json) # print the JSON string representation of the object -print(FormatTest.to_json()) +print(format_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -format_test_dict = format_test_instance.to_dict() +format_test_dict = format_test_instance.model_dump(by_alias=True) # create an instance of FormatTest from a dict -format_test_from_dict = FormatTest.from_dict(format_test_dict) +format_test_from_dict = FormatTest.model_validate(format_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python-httpx/docs/HasOnlyReadOnly.md index fdc48781b15a..66dca11251aa 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/HasOnlyReadOnly.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/HasOnlyReadOnly.md @@ -16,14 +16,14 @@ from petstore_api.models.has_only_read_only import HasOnlyReadOnly # TODO update the JSON string below json = "{}" # create an instance of HasOnlyReadOnly from a JSON string -has_only_read_only_instance = HasOnlyReadOnly.from_json(json) +has_only_read_only_instance = HasOnlyReadOnly.model_validate_json(json) # print the JSON string representation of the object -print(HasOnlyReadOnly.to_json()) +print(has_only_read_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -has_only_read_only_dict = has_only_read_only_instance.to_dict() +has_only_read_only_dict = has_only_read_only_instance.model_dump(by_alias=True) # create an instance of HasOnlyReadOnly from a dict -has_only_read_only_from_dict = HasOnlyReadOnly.from_dict(has_only_read_only_dict) +has_only_read_only_from_dict = HasOnlyReadOnly.model_validate(has_only_read_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python-httpx/docs/HealthCheckResult.md index d4a2b187167f..522156ae5b16 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/HealthCheckResult.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/HealthCheckResult.md @@ -16,14 +16,14 @@ from petstore_api.models.health_check_result import HealthCheckResult # TODO update the JSON string below json = "{}" # create an instance of HealthCheckResult from a JSON string -health_check_result_instance = HealthCheckResult.from_json(json) +health_check_result_instance = HealthCheckResult.model_validate_json(json) # print the JSON string representation of the object -print(HealthCheckResult.to_json()) +print(health_check_result_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -health_check_result_dict = health_check_result_instance.to_dict() +health_check_result_dict = health_check_result_instance.model_dump(by_alias=True) # create an instance of HealthCheckResult from a dict -health_check_result_from_dict = HealthCheckResult.from_dict(health_check_result_dict) +health_check_result_from_dict = HealthCheckResult.model_validate(health_check_result_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/HuntingDog.md b/samples/openapi3/client/petstore/python-httpx/docs/HuntingDog.md index 6db6745dd022..114dfc8575d9 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/HuntingDog.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/HuntingDog.md @@ -15,14 +15,14 @@ from petstore_api.models.hunting_dog import HuntingDog # TODO update the JSON string below json = "{}" # create an instance of HuntingDog from a JSON string -hunting_dog_instance = HuntingDog.from_json(json) +hunting_dog_instance = HuntingDog.model_validate_json(json) # print the JSON string representation of the object -print(HuntingDog.to_json()) +print(hunting_dog_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -hunting_dog_dict = hunting_dog_instance.to_dict() +hunting_dog_dict = hunting_dog_instance.model_dump(by_alias=True) # create an instance of HuntingDog from a dict -hunting_dog_from_dict = HuntingDog.from_dict(hunting_dog_dict) +hunting_dog_from_dict = HuntingDog.model_validate(hunting_dog_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Info.md b/samples/openapi3/client/petstore/python-httpx/docs/Info.md index db88778a9143..160c3633247c 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Info.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Info.md @@ -15,14 +15,14 @@ from petstore_api.models.info import Info # TODO update the JSON string below json = "{}" # create an instance of Info from a JSON string -info_instance = Info.from_json(json) +info_instance = Info.model_validate_json(json) # print the JSON string representation of the object -print(Info.to_json()) +print(info_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -info_dict = info_instance.to_dict() +info_dict = info_instance.model_dump(by_alias=True) # create an instance of Info from a dict -info_from_dict = Info.from_dict(info_dict) +info_from_dict = Info.model_validate(info_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/InnerDictWithProperty.md b/samples/openapi3/client/petstore/python-httpx/docs/InnerDictWithProperty.md index 7b82ebb770b8..79234d754027 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/InnerDictWithProperty.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/InnerDictWithProperty.md @@ -15,14 +15,14 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty # TODO update the JSON string below json = "{}" # create an instance of InnerDictWithProperty from a JSON string -inner_dict_with_property_instance = InnerDictWithProperty.from_json(json) +inner_dict_with_property_instance = InnerDictWithProperty.model_validate_json(json) # print the JSON string representation of the object -print(InnerDictWithProperty.to_json()) +print(inner_dict_with_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -inner_dict_with_property_dict = inner_dict_with_property_instance.to_dict() +inner_dict_with_property_dict = inner_dict_with_property_instance.model_dump(by_alias=True) # create an instance of InnerDictWithProperty from a dict -inner_dict_with_property_from_dict = InnerDictWithProperty.from_dict(inner_dict_with_property_dict) +inner_dict_with_property_from_dict = InnerDictWithProperty.model_validate(inner_dict_with_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/InputAllOf.md b/samples/openapi3/client/petstore/python-httpx/docs/InputAllOf.md index 45298f5308fc..32d4100ac9de 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/InputAllOf.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/InputAllOf.md @@ -15,14 +15,14 @@ from petstore_api.models.input_all_of import InputAllOf # TODO update the JSON string below json = "{}" # create an instance of InputAllOf from a JSON string -input_all_of_instance = InputAllOf.from_json(json) +input_all_of_instance = InputAllOf.model_validate_json(json) # print the JSON string representation of the object -print(InputAllOf.to_json()) +print(input_all_of_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -input_all_of_dict = input_all_of_instance.to_dict() +input_all_of_dict = input_all_of_instance.model_dump(by_alias=True) # create an instance of InputAllOf from a dict -input_all_of_from_dict = InputAllOf.from_dict(input_all_of_dict) +input_all_of_from_dict = InputAllOf.model_validate(input_all_of_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/IntOrString.md b/samples/openapi3/client/petstore/python-httpx/docs/IntOrString.md index b4070b9a8c79..ea8e06339493 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/IntOrString.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/IntOrString.md @@ -14,14 +14,14 @@ from petstore_api.models.int_or_string import IntOrString # TODO update the JSON string below json = "{}" # create an instance of IntOrString from a JSON string -int_or_string_instance = IntOrString.from_json(json) +int_or_string_instance = IntOrString.model_validate_json(json) # print the JSON string representation of the object -print(IntOrString.to_json()) +print(int_or_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -int_or_string_dict = int_or_string_instance.to_dict() +int_or_string_dict = int_or_string_instance.model_dump(by_alias=True) # create an instance of IntOrString from a dict -int_or_string_from_dict = IntOrString.from_dict(int_or_string_dict) +int_or_string_from_dict = IntOrString.model_validate(int_or_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ListClass.md b/samples/openapi3/client/petstore/python-httpx/docs/ListClass.md index 01068b7d22c3..8bc905105efe 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ListClass.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ListClass.md @@ -15,14 +15,14 @@ from petstore_api.models.list_class import ListClass # TODO update the JSON string below json = "{}" # create an instance of ListClass from a JSON string -list_class_instance = ListClass.from_json(json) +list_class_instance = ListClass.model_validate_json(json) # print the JSON string representation of the object -print(ListClass.to_json()) +print(list_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -list_class_dict = list_class_instance.to_dict() +list_class_dict = list_class_instance.model_dump(by_alias=True) # create an instance of ListClass from a dict -list_class_from_dict = ListClass.from_dict(list_class_dict) +list_class_from_dict = ListClass.model_validate(list_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/MapOfArrayOfModel.md b/samples/openapi3/client/petstore/python-httpx/docs/MapOfArrayOfModel.md index 71a4ef66b682..acea13d9a9f5 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/MapOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/MapOfArrayOfModel.md @@ -15,14 +15,14 @@ from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel # TODO update the JSON string below json = "{}" # create an instance of MapOfArrayOfModel from a JSON string -map_of_array_of_model_instance = MapOfArrayOfModel.from_json(json) +map_of_array_of_model_instance = MapOfArrayOfModel.model_validate_json(json) # print the JSON string representation of the object -print(MapOfArrayOfModel.to_json()) +print(map_of_array_of_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -map_of_array_of_model_dict = map_of_array_of_model_instance.to_dict() +map_of_array_of_model_dict = map_of_array_of_model_instance.model_dump(by_alias=True) # create an instance of MapOfArrayOfModel from a dict -map_of_array_of_model_from_dict = MapOfArrayOfModel.from_dict(map_of_array_of_model_dict) +map_of_array_of_model_from_dict = MapOfArrayOfModel.model_validate(map_of_array_of_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/MapTest.md b/samples/openapi3/client/petstore/python-httpx/docs/MapTest.md index d04b82e9378c..fa4501d24286 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/MapTest.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/MapTest.md @@ -18,14 +18,14 @@ from petstore_api.models.map_test import MapTest # TODO update the JSON string below json = "{}" # create an instance of MapTest from a JSON string -map_test_instance = MapTest.from_json(json) +map_test_instance = MapTest.model_validate_json(json) # print the JSON string representation of the object -print(MapTest.to_json()) +print(map_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -map_test_dict = map_test_instance.to_dict() +map_test_dict = map_test_instance.model_dump(by_alias=True) # create an instance of MapTest from a dict -map_test_from_dict = MapTest.from_dict(map_test_dict) +map_test_from_dict = MapTest.model_validate(map_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-httpx/docs/MixedPropertiesAndAdditionalPropertiesClass.md index 84134317aefc..fb354956720a 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -17,14 +17,14 @@ from petstore_api.models.mixed_properties_and_additional_properties_class import # TODO update the JSON string below json = "{}" # create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string -mixed_properties_and_additional_properties_class_instance = MixedPropertiesAndAdditionalPropertiesClass.from_json(json) +mixed_properties_and_additional_properties_class_instance = MixedPropertiesAndAdditionalPropertiesClass.model_validate_json(json) # print the JSON string representation of the object -print(MixedPropertiesAndAdditionalPropertiesClass.to_json()) +print(mixed_properties_and_additional_properties_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -mixed_properties_and_additional_properties_class_dict = mixed_properties_and_additional_properties_class_instance.to_dict() +mixed_properties_and_additional_properties_class_dict = mixed_properties_and_additional_properties_class_instance.model_dump(by_alias=True) # create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict -mixed_properties_and_additional_properties_class_from_dict = MixedPropertiesAndAdditionalPropertiesClass.from_dict(mixed_properties_and_additional_properties_class_dict) +mixed_properties_and_additional_properties_class_from_dict = MixedPropertiesAndAdditionalPropertiesClass.model_validate(mixed_properties_and_additional_properties_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Model200Response.md b/samples/openapi3/client/petstore/python-httpx/docs/Model200Response.md index 7fdbdefc6cec..6cffad7a6d3a 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Model200Response.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Model200Response.md @@ -17,14 +17,14 @@ from petstore_api.models.model200_response import Model200Response # TODO update the JSON string below json = "{}" # create an instance of Model200Response from a JSON string -model200_response_instance = Model200Response.from_json(json) +model200_response_instance = Model200Response.model_validate_json(json) # print the JSON string representation of the object -print(Model200Response.to_json()) +print(model200_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model200_response_dict = model200_response_instance.to_dict() +model200_response_dict = model200_response_instance.model_dump(by_alias=True) # create an instance of Model200Response from a dict -model200_response_from_dict = Model200Response.from_dict(model200_response_dict) +model200_response_from_dict = Model200Response.model_validate(model200_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ModelApiResponse.md b/samples/openapi3/client/petstore/python-httpx/docs/ModelApiResponse.md index 5ddc0db2a0f3..4fdaa910bce4 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ModelApiResponse.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ModelApiResponse.md @@ -17,14 +17,14 @@ from petstore_api.models.model_api_response import ModelApiResponse # TODO update the JSON string below json = "{}" # create an instance of ModelApiResponse from a JSON string -model_api_response_instance = ModelApiResponse.from_json(json) +model_api_response_instance = ModelApiResponse.model_validate_json(json) # print the JSON string representation of the object -print(ModelApiResponse.to_json()) +print(model_api_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_api_response_dict = model_api_response_instance.to_dict() +model_api_response_dict = model_api_response_instance.model_dump(by_alias=True) # create an instance of ModelApiResponse from a dict -model_api_response_from_dict = ModelApiResponse.from_dict(model_api_response_dict) +model_api_response_from_dict = ModelApiResponse.model_validate(model_api_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ModelField.md b/samples/openapi3/client/petstore/python-httpx/docs/ModelField.md index 9073b5dbdb00..43f064bd85a4 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ModelField.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ModelField.md @@ -15,14 +15,14 @@ from petstore_api.models.model_field import ModelField # TODO update the JSON string below json = "{}" # create an instance of ModelField from a JSON string -model_field_instance = ModelField.from_json(json) +model_field_instance = ModelField.model_validate_json(json) # print the JSON string representation of the object -print(ModelField.to_json()) +print(model_field_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_field_dict = model_field_instance.to_dict() +model_field_dict = model_field_instance.model_dump(by_alias=True) # create an instance of ModelField from a dict -model_field_from_dict = ModelField.from_dict(model_field_dict) +model_field_from_dict = ModelField.model_validate(model_field_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ModelReturn.md b/samples/openapi3/client/petstore/python-httpx/docs/ModelReturn.md index 7d327053b0c3..236b2bb971ee 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ModelReturn.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ModelReturn.md @@ -16,14 +16,14 @@ from petstore_api.models.model_return import ModelReturn # TODO update the JSON string below json = "{}" # create an instance of ModelReturn from a JSON string -model_return_instance = ModelReturn.from_json(json) +model_return_instance = ModelReturn.model_validate_json(json) # print the JSON string representation of the object -print(ModelReturn.to_json()) +print(model_return_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_return_dict = model_return_instance.to_dict() +model_return_dict = model_return_instance.model_dump(by_alias=True) # create an instance of ModelReturn from a dict -model_return_from_dict = ModelReturn.from_dict(model_return_dict) +model_return_from_dict = ModelReturn.model_validate(model_return_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/MultiArrays.md b/samples/openapi3/client/petstore/python-httpx/docs/MultiArrays.md index fea5139e7e73..9cf5c5bb1faa 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/MultiArrays.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/MultiArrays.md @@ -16,14 +16,14 @@ from petstore_api.models.multi_arrays import MultiArrays # TODO update the JSON string below json = "{}" # create an instance of MultiArrays from a JSON string -multi_arrays_instance = MultiArrays.from_json(json) +multi_arrays_instance = MultiArrays.model_validate_json(json) # print the JSON string representation of the object -print(MultiArrays.to_json()) +print(multi_arrays_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -multi_arrays_dict = multi_arrays_instance.to_dict() +multi_arrays_dict = multi_arrays_instance.model_dump(by_alias=True) # create an instance of MultiArrays from a dict -multi_arrays_from_dict = MultiArrays.from_dict(multi_arrays_dict) +multi_arrays_from_dict = MultiArrays.model_validate(multi_arrays_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Name.md b/samples/openapi3/client/petstore/python-httpx/docs/Name.md index 5a04ec1ada06..f9d2da4cccd2 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Name.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Name.md @@ -19,14 +19,14 @@ from petstore_api.models.name import Name # TODO update the JSON string below json = "{}" # create an instance of Name from a JSON string -name_instance = Name.from_json(json) +name_instance = Name.model_validate_json(json) # print the JSON string representation of the object -print(Name.to_json()) +print(name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -name_dict = name_instance.to_dict() +name_dict = name_instance.model_dump(by_alias=True) # create an instance of Name from a dict -name_from_dict = Name.from_dict(name_dict) +name_from_dict = Name.model_validate(name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/NullableClass.md b/samples/openapi3/client/petstore/python-httpx/docs/NullableClass.md index 0387dcc2c67a..cd84aa96eb19 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/NullableClass.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/NullableClass.md @@ -27,14 +27,14 @@ from petstore_api.models.nullable_class import NullableClass # TODO update the JSON string below json = "{}" # create an instance of NullableClass from a JSON string -nullable_class_instance = NullableClass.from_json(json) +nullable_class_instance = NullableClass.model_validate_json(json) # print the JSON string representation of the object -print(NullableClass.to_json()) +print(nullable_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -nullable_class_dict = nullable_class_instance.to_dict() +nullable_class_dict = nullable_class_instance.model_dump(by_alias=True) # create an instance of NullableClass from a dict -nullable_class_from_dict = NullableClass.from_dict(nullable_class_dict) +nullable_class_from_dict = NullableClass.model_validate(nullable_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/NullableProperty.md b/samples/openapi3/client/petstore/python-httpx/docs/NullableProperty.md index 30edaf4844b2..c0ef9b80fcb5 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/NullableProperty.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/NullableProperty.md @@ -16,14 +16,14 @@ from petstore_api.models.nullable_property import NullableProperty # TODO update the JSON string below json = "{}" # create an instance of NullableProperty from a JSON string -nullable_property_instance = NullableProperty.from_json(json) +nullable_property_instance = NullableProperty.model_validate_json(json) # print the JSON string representation of the object -print(NullableProperty.to_json()) +print(nullable_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -nullable_property_dict = nullable_property_instance.to_dict() +nullable_property_dict = nullable_property_instance.model_dump(by_alias=True) # create an instance of NullableProperty from a dict -nullable_property_from_dict = NullableProperty.from_dict(nullable_property_dict) +nullable_property_from_dict = NullableProperty.model_validate(nullable_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/NumberOnly.md b/samples/openapi3/client/petstore/python-httpx/docs/NumberOnly.md index 415dd25585d4..f1caf70ea2b7 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/NumberOnly.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/NumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.number_only import NumberOnly # TODO update the JSON string below json = "{}" # create an instance of NumberOnly from a JSON string -number_only_instance = NumberOnly.from_json(json) +number_only_instance = NumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(NumberOnly.to_json()) +print(number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -number_only_dict = number_only_instance.to_dict() +number_only_dict = number_only_instance.model_dump(by_alias=True) # create an instance of NumberOnly from a dict -number_only_from_dict = NumberOnly.from_dict(number_only_dict) +number_only_from_dict = NumberOnly.model_validate(number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ObjectToTestAdditionalProperties.md b/samples/openapi3/client/petstore/python-httpx/docs/ObjectToTestAdditionalProperties.md index f6bc34c98e65..f201a9627dc3 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ObjectToTestAdditionalProperties.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ObjectToTestAdditionalProperties.md @@ -16,14 +16,14 @@ from petstore_api.models.object_to_test_additional_properties import ObjectToTes # TODO update the JSON string below json = "{}" # create an instance of ObjectToTestAdditionalProperties from a JSON string -object_to_test_additional_properties_instance = ObjectToTestAdditionalProperties.from_json(json) +object_to_test_additional_properties_instance = ObjectToTestAdditionalProperties.model_validate_json(json) # print the JSON string representation of the object -print(ObjectToTestAdditionalProperties.to_json()) +print(object_to_test_additional_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -object_to_test_additional_properties_dict = object_to_test_additional_properties_instance.to_dict() +object_to_test_additional_properties_dict = object_to_test_additional_properties_instance.model_dump(by_alias=True) # create an instance of ObjectToTestAdditionalProperties from a dict -object_to_test_additional_properties_from_dict = ObjectToTestAdditionalProperties.from_dict(object_to_test_additional_properties_dict) +object_to_test_additional_properties_from_dict = ObjectToTestAdditionalProperties.model_validate(object_to_test_additional_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ObjectWithDeprecatedFields.md b/samples/openapi3/client/petstore/python-httpx/docs/ObjectWithDeprecatedFields.md index 6dbd2ace04f1..86cce93ba775 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ObjectWithDeprecatedFields.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ObjectWithDeprecatedFields.md @@ -18,14 +18,14 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecat # TODO update the JSON string below json = "{}" # create an instance of ObjectWithDeprecatedFields from a JSON string -object_with_deprecated_fields_instance = ObjectWithDeprecatedFields.from_json(json) +object_with_deprecated_fields_instance = ObjectWithDeprecatedFields.model_validate_json(json) # print the JSON string representation of the object -print(ObjectWithDeprecatedFields.to_json()) +print(object_with_deprecated_fields_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -object_with_deprecated_fields_dict = object_with_deprecated_fields_instance.to_dict() +object_with_deprecated_fields_dict = object_with_deprecated_fields_instance.model_dump(by_alias=True) # create an instance of ObjectWithDeprecatedFields from a dict -object_with_deprecated_fields_from_dict = ObjectWithDeprecatedFields.from_dict(object_with_deprecated_fields_dict) +object_with_deprecated_fields_from_dict = ObjectWithDeprecatedFields.model_validate(object_with_deprecated_fields_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Order.md b/samples/openapi3/client/petstore/python-httpx/docs/Order.md index 00526b8d04b9..f5410bc8d0f3 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Order.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Order.md @@ -20,14 +20,14 @@ from petstore_api.models.order import Order # TODO update the JSON string below json = "{}" # create an instance of Order from a JSON string -order_instance = Order.from_json(json) +order_instance = Order.model_validate_json(json) # print the JSON string representation of the object -print(Order.to_json()) +print(order_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -order_dict = order_instance.to_dict() +order_dict = order_instance.model_dump(by_alias=True) # create an instance of Order from a dict -order_from_dict = Order.from_dict(order_dict) +order_from_dict = Order.model_validate(order_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/OuterComposite.md b/samples/openapi3/client/petstore/python-httpx/docs/OuterComposite.md index c8242c2d2653..9df82e2abc87 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/OuterComposite.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/OuterComposite.md @@ -17,14 +17,14 @@ from petstore_api.models.outer_composite import OuterComposite # TODO update the JSON string below json = "{}" # create an instance of OuterComposite from a JSON string -outer_composite_instance = OuterComposite.from_json(json) +outer_composite_instance = OuterComposite.model_validate_json(json) # print the JSON string representation of the object -print(OuterComposite.to_json()) +print(outer_composite_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -outer_composite_dict = outer_composite_instance.to_dict() +outer_composite_dict = outer_composite_instance.model_dump(by_alias=True) # create an instance of OuterComposite from a dict -outer_composite_from_dict = OuterComposite.from_dict(outer_composite_dict) +outer_composite_from_dict = OuterComposite.model_validate(outer_composite_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/OuterObjectWithEnumProperty.md b/samples/openapi3/client/petstore/python-httpx/docs/OuterObjectWithEnumProperty.md index 6137dbd98da6..d23ccc3757bb 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/OuterObjectWithEnumProperty.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/OuterObjectWithEnumProperty.md @@ -16,14 +16,14 @@ from petstore_api.models.outer_object_with_enum_property import OuterObjectWithE # TODO update the JSON string below json = "{}" # create an instance of OuterObjectWithEnumProperty from a JSON string -outer_object_with_enum_property_instance = OuterObjectWithEnumProperty.from_json(json) +outer_object_with_enum_property_instance = OuterObjectWithEnumProperty.model_validate_json(json) # print the JSON string representation of the object -print(OuterObjectWithEnumProperty.to_json()) +print(outer_object_with_enum_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -outer_object_with_enum_property_dict = outer_object_with_enum_property_instance.to_dict() +outer_object_with_enum_property_dict = outer_object_with_enum_property_instance.model_dump(by_alias=True) # create an instance of OuterObjectWithEnumProperty from a dict -outer_object_with_enum_property_from_dict = OuterObjectWithEnumProperty.from_dict(outer_object_with_enum_property_dict) +outer_object_with_enum_property_from_dict = OuterObjectWithEnumProperty.model_validate(outer_object_with_enum_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Parent.md b/samples/openapi3/client/petstore/python-httpx/docs/Parent.md index 7387f9250aad..21df089ea756 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Parent.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Parent.md @@ -15,14 +15,14 @@ from petstore_api.models.parent import Parent # TODO update the JSON string below json = "{}" # create an instance of Parent from a JSON string -parent_instance = Parent.from_json(json) +parent_instance = Parent.model_validate_json(json) # print the JSON string representation of the object -print(Parent.to_json()) +print(parent_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -parent_dict = parent_instance.to_dict() +parent_dict = parent_instance.model_dump(by_alias=True) # create an instance of Parent from a dict -parent_from_dict = Parent.from_dict(parent_dict) +parent_from_dict = Parent.model_validate(parent_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ParentWithOptionalDict.md b/samples/openapi3/client/petstore/python-httpx/docs/ParentWithOptionalDict.md index bfc8688ea26f..a6ee19fd1a74 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ParentWithOptionalDict.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ParentWithOptionalDict.md @@ -15,14 +15,14 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict # TODO update the JSON string below json = "{}" # create an instance of ParentWithOptionalDict from a JSON string -parent_with_optional_dict_instance = ParentWithOptionalDict.from_json(json) +parent_with_optional_dict_instance = ParentWithOptionalDict.model_validate_json(json) # print the JSON string representation of the object -print(ParentWithOptionalDict.to_json()) +print(parent_with_optional_dict_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -parent_with_optional_dict_dict = parent_with_optional_dict_instance.to_dict() +parent_with_optional_dict_dict = parent_with_optional_dict_instance.model_dump(by_alias=True) # create an instance of ParentWithOptionalDict from a dict -parent_with_optional_dict_from_dict = ParentWithOptionalDict.from_dict(parent_with_optional_dict_dict) +parent_with_optional_dict_from_dict = ParentWithOptionalDict.model_validate(parent_with_optional_dict_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Pet.md b/samples/openapi3/client/petstore/python-httpx/docs/Pet.md index 5329cf2fb925..179b71891d9d 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Pet.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Pet.md @@ -20,14 +20,14 @@ from petstore_api.models.pet import Pet # TODO update the JSON string below json = "{}" # create an instance of Pet from a JSON string -pet_instance = Pet.from_json(json) +pet_instance = Pet.model_validate_json(json) # print the JSON string representation of the object -print(Pet.to_json()) +print(pet_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pet_dict = pet_instance.to_dict() +pet_dict = pet_instance.model_dump(by_alias=True) # create an instance of Pet from a dict -pet_from_dict = Pet.from_dict(pet_dict) +pet_from_dict = Pet.model_validate(pet_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Pig.md b/samples/openapi3/client/petstore/python-httpx/docs/Pig.md index 625930676083..2e275198c547 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Pig.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Pig.md @@ -17,14 +17,14 @@ from petstore_api.models.pig import Pig # TODO update the JSON string below json = "{}" # create an instance of Pig from a JSON string -pig_instance = Pig.from_json(json) +pig_instance = Pig.model_validate_json(json) # print the JSON string representation of the object -print(Pig.to_json()) +print(pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pig_dict = pig_instance.to_dict() +pig_dict = pig_instance.model_dump(by_alias=True) # create an instance of Pig from a dict -pig_from_dict = Pig.from_dict(pig_dict) +pig_from_dict = Pig.model_validate(pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/PonySizes.md b/samples/openapi3/client/petstore/python-httpx/docs/PonySizes.md index ced44c872060..6bb28b418b6d 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/PonySizes.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/PonySizes.md @@ -15,14 +15,14 @@ from petstore_api.models.pony_sizes import PonySizes # TODO update the JSON string below json = "{}" # create an instance of PonySizes from a JSON string -pony_sizes_instance = PonySizes.from_json(json) +pony_sizes_instance = PonySizes.model_validate_json(json) # print the JSON string representation of the object -print(PonySizes.to_json()) +print(pony_sizes_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pony_sizes_dict = pony_sizes_instance.to_dict() +pony_sizes_dict = pony_sizes_instance.model_dump(by_alias=True) # create an instance of PonySizes from a dict -pony_sizes_from_dict = PonySizes.from_dict(pony_sizes_dict) +pony_sizes_from_dict = PonySizes.model_validate(pony_sizes_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/PoopCleaning.md b/samples/openapi3/client/petstore/python-httpx/docs/PoopCleaning.md index 8f9c25e08316..3bf20593f929 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/PoopCleaning.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/PoopCleaning.md @@ -17,14 +17,14 @@ from petstore_api.models.poop_cleaning import PoopCleaning # TODO update the JSON string below json = "{}" # create an instance of PoopCleaning from a JSON string -poop_cleaning_instance = PoopCleaning.from_json(json) +poop_cleaning_instance = PoopCleaning.model_validate_json(json) # print the JSON string representation of the object -print(PoopCleaning.to_json()) +print(poop_cleaning_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -poop_cleaning_dict = poop_cleaning_instance.to_dict() +poop_cleaning_dict = poop_cleaning_instance.model_dump(by_alias=True) # create an instance of PoopCleaning from a dict -poop_cleaning_from_dict = PoopCleaning.from_dict(poop_cleaning_dict) +poop_cleaning_from_dict = PoopCleaning.model_validate(poop_cleaning_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/PrimitiveString.md b/samples/openapi3/client/petstore/python-httpx/docs/PrimitiveString.md index 85ceb632e167..a1a9a3dc81b6 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/PrimitiveString.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/PrimitiveString.md @@ -15,14 +15,14 @@ from petstore_api.models.primitive_string import PrimitiveString # TODO update the JSON string below json = "{}" # create an instance of PrimitiveString from a JSON string -primitive_string_instance = PrimitiveString.from_json(json) +primitive_string_instance = PrimitiveString.model_validate_json(json) # print the JSON string representation of the object -print(PrimitiveString.to_json()) +print(primitive_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -primitive_string_dict = primitive_string_instance.to_dict() +primitive_string_dict = primitive_string_instance.model_dump(by_alias=True) # create an instance of PrimitiveString from a dict -primitive_string_from_dict = PrimitiveString.from_dict(primitive_string_dict) +primitive_string_from_dict = PrimitiveString.model_validate(primitive_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/PropertyMap.md b/samples/openapi3/client/petstore/python-httpx/docs/PropertyMap.md index a55a0e5c6f01..5fcda1f7803d 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/PropertyMap.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/PropertyMap.md @@ -15,14 +15,14 @@ from petstore_api.models.property_map import PropertyMap # TODO update the JSON string below json = "{}" # create an instance of PropertyMap from a JSON string -property_map_instance = PropertyMap.from_json(json) +property_map_instance = PropertyMap.model_validate_json(json) # print the JSON string representation of the object -print(PropertyMap.to_json()) +print(property_map_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -property_map_dict = property_map_instance.to_dict() +property_map_dict = property_map_instance.model_dump(by_alias=True) # create an instance of PropertyMap from a dict -property_map_from_dict = PropertyMap.from_dict(property_map_dict) +property_map_from_dict = PropertyMap.model_validate(property_map_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/PropertyNameCollision.md b/samples/openapi3/client/petstore/python-httpx/docs/PropertyNameCollision.md index 40c233670dd0..a4a8405fe847 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/PropertyNameCollision.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/PropertyNameCollision.md @@ -17,14 +17,14 @@ from petstore_api.models.property_name_collision import PropertyNameCollision # TODO update the JSON string below json = "{}" # create an instance of PropertyNameCollision from a JSON string -property_name_collision_instance = PropertyNameCollision.from_json(json) +property_name_collision_instance = PropertyNameCollision.model_validate_json(json) # print the JSON string representation of the object -print(PropertyNameCollision.to_json()) +print(property_name_collision_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -property_name_collision_dict = property_name_collision_instance.to_dict() +property_name_collision_dict = property_name_collision_instance.model_dump(by_alias=True) # create an instance of PropertyNameCollision from a dict -property_name_collision_from_dict = PropertyNameCollision.from_dict(property_name_collision_dict) +property_name_collision_from_dict = PropertyNameCollision.model_validate(property_name_collision_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python-httpx/docs/ReadOnlyFirst.md index 686ec5da41c9..e55fe102b673 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/ReadOnlyFirst.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/ReadOnlyFirst.md @@ -16,14 +16,14 @@ from petstore_api.models.read_only_first import ReadOnlyFirst # TODO update the JSON string below json = "{}" # create an instance of ReadOnlyFirst from a JSON string -read_only_first_instance = ReadOnlyFirst.from_json(json) +read_only_first_instance = ReadOnlyFirst.model_validate_json(json) # print the JSON string representation of the object -print(ReadOnlyFirst.to_json()) +print(read_only_first_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -read_only_first_dict = read_only_first_instance.to_dict() +read_only_first_dict = read_only_first_instance.model_dump(by_alias=True) # create an instance of ReadOnlyFirst from a dict -read_only_first_from_dict = ReadOnlyFirst.from_dict(read_only_first_dict) +read_only_first_from_dict = ReadOnlyFirst.model_validate(read_only_first_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/SecondCircularAllOfRef.md b/samples/openapi3/client/petstore/python-httpx/docs/SecondCircularAllOfRef.md index 65ebdd4c7e1d..47fb4daf97a4 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/SecondCircularAllOfRef.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/SecondCircularAllOfRef.md @@ -16,14 +16,14 @@ from petstore_api.models.second_circular_all_of_ref import SecondCircularAllOfRe # TODO update the JSON string below json = "{}" # create an instance of SecondCircularAllOfRef from a JSON string -second_circular_all_of_ref_instance = SecondCircularAllOfRef.from_json(json) +second_circular_all_of_ref_instance = SecondCircularAllOfRef.model_validate_json(json) # print the JSON string representation of the object -print(SecondCircularAllOfRef.to_json()) +print(second_circular_all_of_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -second_circular_all_of_ref_dict = second_circular_all_of_ref_instance.to_dict() +second_circular_all_of_ref_dict = second_circular_all_of_ref_instance.model_dump(by_alias=True) # create an instance of SecondCircularAllOfRef from a dict -second_circular_all_of_ref_from_dict = SecondCircularAllOfRef.from_dict(second_circular_all_of_ref_dict) +second_circular_all_of_ref_from_dict = SecondCircularAllOfRef.model_validate(second_circular_all_of_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/SecondRef.md b/samples/openapi3/client/petstore/python-httpx/docs/SecondRef.md index dfb1a0ac6db5..fa0b9f285e0c 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/SecondRef.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/SecondRef.md @@ -16,14 +16,14 @@ from petstore_api.models.second_ref import SecondRef # TODO update the JSON string below json = "{}" # create an instance of SecondRef from a JSON string -second_ref_instance = SecondRef.from_json(json) +second_ref_instance = SecondRef.model_validate_json(json) # print the JSON string representation of the object -print(SecondRef.to_json()) +print(second_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -second_ref_dict = second_ref_instance.to_dict() +second_ref_dict = second_ref_instance.model_dump(by_alias=True) # create an instance of SecondRef from a dict -second_ref_from_dict = SecondRef.from_dict(second_ref_dict) +second_ref_from_dict = SecondRef.model_validate(second_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/SelfReferenceModel.md b/samples/openapi3/client/petstore/python-httpx/docs/SelfReferenceModel.md index 208cdac04b6f..af3c77d0524b 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/SelfReferenceModel.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/SelfReferenceModel.md @@ -16,14 +16,14 @@ from petstore_api.models.self_reference_model import SelfReferenceModel # TODO update the JSON string below json = "{}" # create an instance of SelfReferenceModel from a JSON string -self_reference_model_instance = SelfReferenceModel.from_json(json) +self_reference_model_instance = SelfReferenceModel.model_validate_json(json) # print the JSON string representation of the object -print(SelfReferenceModel.to_json()) +print(self_reference_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -self_reference_model_dict = self_reference_model_instance.to_dict() +self_reference_model_dict = self_reference_model_instance.model_dump(by_alias=True) # create an instance of SelfReferenceModel from a dict -self_reference_model_from_dict = SelfReferenceModel.from_dict(self_reference_model_dict) +self_reference_model_from_dict = SelfReferenceModel.model_validate(self_reference_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python-httpx/docs/SpecialModelName.md index 35303f34efd2..589dbeb14b94 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/SpecialModelName.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/SpecialModelName.md @@ -15,14 +15,14 @@ from petstore_api.models.special_model_name import SpecialModelName # TODO update the JSON string below json = "{}" # create an instance of SpecialModelName from a JSON string -special_model_name_instance = SpecialModelName.from_json(json) +special_model_name_instance = SpecialModelName.model_validate_json(json) # print the JSON string representation of the object -print(SpecialModelName.to_json()) +print(special_model_name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -special_model_name_dict = special_model_name_instance.to_dict() +special_model_name_dict = special_model_name_instance.model_dump(by_alias=True) # create an instance of SpecialModelName from a dict -special_model_name_from_dict = SpecialModelName.from_dict(special_model_name_dict) +special_model_name_from_dict = SpecialModelName.model_validate(special_model_name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/SpecialName.md b/samples/openapi3/client/petstore/python-httpx/docs/SpecialName.md index ccc550b16e33..19da9016451c 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/SpecialName.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/SpecialName.md @@ -17,14 +17,14 @@ from petstore_api.models.special_name import SpecialName # TODO update the JSON string below json = "{}" # create an instance of SpecialName from a JSON string -special_name_instance = SpecialName.from_json(json) +special_name_instance = SpecialName.model_validate_json(json) # print the JSON string representation of the object -print(SpecialName.to_json()) +print(special_name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -special_name_dict = special_name_instance.to_dict() +special_name_dict = special_name_instance.model_dump(by_alias=True) # create an instance of SpecialName from a dict -special_name_from_dict = SpecialName.from_dict(special_name_dict) +special_name_from_dict = SpecialName.model_validate(special_name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Tag.md b/samples/openapi3/client/petstore/python-httpx/docs/Tag.md index 4106d9cfe5db..66339d14c875 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Tag.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Tag.md @@ -16,14 +16,14 @@ from petstore_api.models.tag import Tag # TODO update the JSON string below json = "{}" # create an instance of Tag from a JSON string -tag_instance = Tag.from_json(json) +tag_instance = Tag.model_validate_json(json) # print the JSON string representation of the object -print(Tag.to_json()) +print(tag_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tag_dict = tag_instance.to_dict() +tag_dict = tag_instance.model_dump(by_alias=True) # create an instance of Tag from a dict -tag_from_dict = Tag.from_dict(tag_dict) +tag_from_dict = Tag.model_validate(tag_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Task.md b/samples/openapi3/client/petstore/python-httpx/docs/Task.md index 85fa2776a059..229ed6510a11 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Task.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Task.md @@ -17,14 +17,14 @@ from petstore_api.models.task import Task # TODO update the JSON string below json = "{}" # create an instance of Task from a JSON string -task_instance = Task.from_json(json) +task_instance = Task.model_validate_json(json) # print the JSON string representation of the object -print(Task.to_json()) +print(task_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -task_dict = task_instance.to_dict() +task_dict = task_instance.model_dump(by_alias=True) # create an instance of Task from a dict -task_from_dict = Task.from_dict(task_dict) +task_from_dict = Task.model_validate(task_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/TaskActivity.md b/samples/openapi3/client/petstore/python-httpx/docs/TaskActivity.md index e905a477292d..c025d32ba436 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/TaskActivity.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/TaskActivity.md @@ -17,14 +17,14 @@ from petstore_api.models.task_activity import TaskActivity # TODO update the JSON string below json = "{}" # create an instance of TaskActivity from a JSON string -task_activity_instance = TaskActivity.from_json(json) +task_activity_instance = TaskActivity.model_validate_json(json) # print the JSON string representation of the object -print(TaskActivity.to_json()) +print(task_activity_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -task_activity_dict = task_activity_instance.to_dict() +task_activity_dict = task_activity_instance.model_dump(by_alias=True) # create an instance of TaskActivity from a dict -task_activity_from_dict = TaskActivity.from_dict(task_activity_dict) +task_activity_from_dict = TaskActivity.model_validate(task_activity_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/TestErrorResponsesWithModel400Response.md b/samples/openapi3/client/petstore/python-httpx/docs/TestErrorResponsesWithModel400Response.md index be416bbad0f7..fed06705b55b 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/TestErrorResponsesWithModel400Response.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/TestErrorResponsesWithModel400Response.md @@ -15,14 +15,14 @@ from petstore_api.models.test_error_responses_with_model400_response import Test # TODO update the JSON string below json = "{}" # create an instance of TestErrorResponsesWithModel400Response from a JSON string -test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.from_json(json) +test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.model_validate_json(json) # print the JSON string representation of the object -print(TestErrorResponsesWithModel400Response.to_json()) +print(test_error_responses_with_model400_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.to_dict() +test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.model_dump(by_alias=True) # create an instance of TestErrorResponsesWithModel400Response from a dict -test_error_responses_with_model400_response_from_dict = TestErrorResponsesWithModel400Response.from_dict(test_error_responses_with_model400_response_dict) +test_error_responses_with_model400_response_from_dict = TestErrorResponsesWithModel400Response.model_validate(test_error_responses_with_model400_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/TestErrorResponsesWithModel404Response.md b/samples/openapi3/client/petstore/python-httpx/docs/TestErrorResponsesWithModel404Response.md index 1c984f847bf1..8813e0792d22 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/TestErrorResponsesWithModel404Response.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/TestErrorResponsesWithModel404Response.md @@ -15,14 +15,14 @@ from petstore_api.models.test_error_responses_with_model404_response import Test # TODO update the JSON string below json = "{}" # create an instance of TestErrorResponsesWithModel404Response from a JSON string -test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.from_json(json) +test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.model_validate_json(json) # print the JSON string representation of the object -print(TestErrorResponsesWithModel404Response.to_json()) +print(test_error_responses_with_model404_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.to_dict() +test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.model_dump(by_alias=True) # create an instance of TestErrorResponsesWithModel404Response from a dict -test_error_responses_with_model404_response_from_dict = TestErrorResponsesWithModel404Response.from_dict(test_error_responses_with_model404_response_dict) +test_error_responses_with_model404_response_from_dict = TestErrorResponsesWithModel404Response.model_validate(test_error_responses_with_model404_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/TestInlineFreeformAdditionalPropertiesRequest.md b/samples/openapi3/client/petstore/python-httpx/docs/TestInlineFreeformAdditionalPropertiesRequest.md index 511132d689be..870cd8850e6b 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/TestInlineFreeformAdditionalPropertiesRequest.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -15,14 +15,14 @@ from petstore_api.models.test_inline_freeform_additional_properties_request impo # TODO update the JSON string below json = "{}" # create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string -test_inline_freeform_additional_properties_request_instance = TestInlineFreeformAdditionalPropertiesRequest.from_json(json) +test_inline_freeform_additional_properties_request_instance = TestInlineFreeformAdditionalPropertiesRequest.model_validate_json(json) # print the JSON string representation of the object -print(TestInlineFreeformAdditionalPropertiesRequest.to_json()) +print(test_inline_freeform_additional_properties_request_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_inline_freeform_additional_properties_request_dict = test_inline_freeform_additional_properties_request_instance.to_dict() +test_inline_freeform_additional_properties_request_dict = test_inline_freeform_additional_properties_request_instance.model_dump(by_alias=True) # create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict -test_inline_freeform_additional_properties_request_from_dict = TestInlineFreeformAdditionalPropertiesRequest.from_dict(test_inline_freeform_additional_properties_request_dict) +test_inline_freeform_additional_properties_request_from_dict = TestInlineFreeformAdditionalPropertiesRequest.model_validate(test_inline_freeform_additional_properties_request_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/TestModelWithEnumDefault.md b/samples/openapi3/client/petstore/python-httpx/docs/TestModelWithEnumDefault.md index 7d46e86deba4..1f63056fe0f1 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/TestModelWithEnumDefault.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/TestModelWithEnumDefault.md @@ -19,14 +19,14 @@ from petstore_api.models.test_model_with_enum_default import TestModelWithEnumDe # TODO update the JSON string below json = "{}" # create an instance of TestModelWithEnumDefault from a JSON string -test_model_with_enum_default_instance = TestModelWithEnumDefault.from_json(json) +test_model_with_enum_default_instance = TestModelWithEnumDefault.model_validate_json(json) # print the JSON string representation of the object -print(TestModelWithEnumDefault.to_json()) +print(test_model_with_enum_default_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_model_with_enum_default_dict = test_model_with_enum_default_instance.to_dict() +test_model_with_enum_default_dict = test_model_with_enum_default_instance.model_dump(by_alias=True) # create an instance of TestModelWithEnumDefault from a dict -test_model_with_enum_default_from_dict = TestModelWithEnumDefault.from_dict(test_model_with_enum_default_dict) +test_model_with_enum_default_from_dict = TestModelWithEnumDefault.model_validate(test_model_with_enum_default_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/TestObjectForMultipartRequestsRequestMarker.md b/samples/openapi3/client/petstore/python-httpx/docs/TestObjectForMultipartRequestsRequestMarker.md index ff0ca9ee00ac..bb685d44835a 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/TestObjectForMultipartRequestsRequestMarker.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/TestObjectForMultipartRequestsRequestMarker.md @@ -15,14 +15,14 @@ from petstore_api.models.test_object_for_multipart_requests_request_marker impor # TODO update the JSON string below json = "{}" # create an instance of TestObjectForMultipartRequestsRequestMarker from a JSON string -test_object_for_multipart_requests_request_marker_instance = TestObjectForMultipartRequestsRequestMarker.from_json(json) +test_object_for_multipart_requests_request_marker_instance = TestObjectForMultipartRequestsRequestMarker.model_validate_json(json) # print the JSON string representation of the object -print(TestObjectForMultipartRequestsRequestMarker.to_json()) +print(test_object_for_multipart_requests_request_marker_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_object_for_multipart_requests_request_marker_dict = test_object_for_multipart_requests_request_marker_instance.to_dict() +test_object_for_multipart_requests_request_marker_dict = test_object_for_multipart_requests_request_marker_instance.model_dump(by_alias=True) # create an instance of TestObjectForMultipartRequestsRequestMarker from a dict -test_object_for_multipart_requests_request_marker_from_dict = TestObjectForMultipartRequestsRequestMarker.from_dict(test_object_for_multipart_requests_request_marker_dict) +test_object_for_multipart_requests_request_marker_from_dict = TestObjectForMultipartRequestsRequestMarker.model_validate(test_object_for_multipart_requests_request_marker_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/Tiger.md b/samples/openapi3/client/petstore/python-httpx/docs/Tiger.md index f1cf2133f0f7..90c7d8770979 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/Tiger.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/Tiger.md @@ -15,14 +15,14 @@ from petstore_api.models.tiger import Tiger # TODO update the JSON string below json = "{}" # create an instance of Tiger from a JSON string -tiger_instance = Tiger.from_json(json) +tiger_instance = Tiger.model_validate_json(json) # print the JSON string representation of the object -print(Tiger.to_json()) +print(tiger_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tiger_dict = tiger_instance.to_dict() +tiger_dict = tiger_instance.model_dump(by_alias=True) # create an instance of Tiger from a dict -tiger_from_dict = Tiger.from_dict(tiger_dict) +tiger_from_dict = Tiger.model_validate(tiger_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/UnnamedDictWithAdditionalModelListProperties.md b/samples/openapi3/client/petstore/python-httpx/docs/UnnamedDictWithAdditionalModelListProperties.md index 68cd00ab0a7a..0b411bf5df7b 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/UnnamedDictWithAdditionalModelListProperties.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/UnnamedDictWithAdditionalModelListProperties.md @@ -15,14 +15,14 @@ from petstore_api.models.unnamed_dict_with_additional_model_list_properties impo # TODO update the JSON string below json = "{}" # create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string -unnamed_dict_with_additional_model_list_properties_instance = UnnamedDictWithAdditionalModelListProperties.from_json(json) +unnamed_dict_with_additional_model_list_properties_instance = UnnamedDictWithAdditionalModelListProperties.model_validate_json(json) # print the JSON string representation of the object -print(UnnamedDictWithAdditionalModelListProperties.to_json()) +print(unnamed_dict_with_additional_model_list_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -unnamed_dict_with_additional_model_list_properties_dict = unnamed_dict_with_additional_model_list_properties_instance.to_dict() +unnamed_dict_with_additional_model_list_properties_dict = unnamed_dict_with_additional_model_list_properties_instance.model_dump(by_alias=True) # create an instance of UnnamedDictWithAdditionalModelListProperties from a dict -unnamed_dict_with_additional_model_list_properties_from_dict = UnnamedDictWithAdditionalModelListProperties.from_dict(unnamed_dict_with_additional_model_list_properties_dict) +unnamed_dict_with_additional_model_list_properties_from_dict = UnnamedDictWithAdditionalModelListProperties.model_validate(unnamed_dict_with_additional_model_list_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/UnnamedDictWithAdditionalStringListProperties.md b/samples/openapi3/client/petstore/python-httpx/docs/UnnamedDictWithAdditionalStringListProperties.md index 045b0e22ad09..def639720586 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/UnnamedDictWithAdditionalStringListProperties.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/UnnamedDictWithAdditionalStringListProperties.md @@ -15,14 +15,14 @@ from petstore_api.models.unnamed_dict_with_additional_string_list_properties imp # TODO update the JSON string below json = "{}" # create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string -unnamed_dict_with_additional_string_list_properties_instance = UnnamedDictWithAdditionalStringListProperties.from_json(json) +unnamed_dict_with_additional_string_list_properties_instance = UnnamedDictWithAdditionalStringListProperties.model_validate_json(json) # print the JSON string representation of the object -print(UnnamedDictWithAdditionalStringListProperties.to_json()) +print(unnamed_dict_with_additional_string_list_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -unnamed_dict_with_additional_string_list_properties_dict = unnamed_dict_with_additional_string_list_properties_instance.to_dict() +unnamed_dict_with_additional_string_list_properties_dict = unnamed_dict_with_additional_string_list_properties_instance.model_dump(by_alias=True) # create an instance of UnnamedDictWithAdditionalStringListProperties from a dict -unnamed_dict_with_additional_string_list_properties_from_dict = UnnamedDictWithAdditionalStringListProperties.from_dict(unnamed_dict_with_additional_string_list_properties_dict) +unnamed_dict_with_additional_string_list_properties_from_dict = UnnamedDictWithAdditionalStringListProperties.model_validate(unnamed_dict_with_additional_string_list_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python-httpx/docs/UploadFileWithAdditionalPropertiesRequestObject.md index 141027780371..35be1642e660 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/UploadFileWithAdditionalPropertiesRequestObject.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -16,14 +16,14 @@ from petstore_api.models.upload_file_with_additional_properties_request_object i # TODO update the JSON string below json = "{}" # create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string -upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.from_json(json) +upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.model_validate_json(json) # print the JSON string representation of the object -print(UploadFileWithAdditionalPropertiesRequestObject.to_json()) +print(upload_file_with_additional_properties_request_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.to_dict() +upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.model_dump(by_alias=True) # create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict -upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.from_dict(upload_file_with_additional_properties_request_object_dict) +upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.model_validate(upload_file_with_additional_properties_request_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/User.md b/samples/openapi3/client/petstore/python-httpx/docs/User.md index c45d26d27043..8f4ae3d04712 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/User.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/User.md @@ -22,14 +22,14 @@ from petstore_api.models.user import User # TODO update the JSON string below json = "{}" # create an instance of User from a JSON string -user_instance = User.from_json(json) +user_instance = User.model_validate_json(json) # print the JSON string representation of the object -print(User.to_json()) +print(user_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -user_dict = user_instance.to_dict() +user_dict = user_instance.model_dump(by_alias=True) # create an instance of User from a dict -user_from_dict = User.from_dict(user_dict) +user_from_dict = User.model_validate(user_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/docs/WithNestedOneOf.md b/samples/openapi3/client/petstore/python-httpx/docs/WithNestedOneOf.md index e7bbbc28fc2d..12d648bb920d 100644 --- a/samples/openapi3/client/petstore/python-httpx/docs/WithNestedOneOf.md +++ b/samples/openapi3/client/petstore/python-httpx/docs/WithNestedOneOf.md @@ -17,14 +17,14 @@ from petstore_api.models.with_nested_one_of import WithNestedOneOf # TODO update the JSON string below json = "{}" # create an instance of WithNestedOneOf from a JSON string -with_nested_one_of_instance = WithNestedOneOf.from_json(json) +with_nested_one_of_instance = WithNestedOneOf.model_validate_json(json) # print the JSON string representation of the object -print(WithNestedOneOf.to_json()) +print(with_nested_one_of_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -with_nested_one_of_dict = with_nested_one_of_instance.to_dict() +with_nested_one_of_dict = with_nested_one_of_instance.model_dump(by_alias=True) # create an instance of WithNestedOneOf from a dict -with_nested_one_of_from_dict = WithNestedOneOf.from_dict(with_nested_one_of_dict) +with_nested_one_of_from_dict = WithNestedOneOf.model_validate(with_nested_one_of_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/api_client.py index bbdb918c7c5e..62440d5e858c 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/api_client.py @@ -717,7 +717,7 @@ def __deserialize_file(self, response): content_disposition ) assert m is not None, "Unexpected 'content-disposition' header value" - filename = m.group(1) + filename = os.path.basename(m.group(1)) # Strip any directory traversal path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_any_type.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_any_type.py index 291b5e55e353..d3c2e0c15c8d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_any_type.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_any_type.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesAnyType(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesAnyType(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesAnyType from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesAnyType from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_class.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_class.py index 4b2cc457e499..1b96696ac069 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_class.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesClass(BaseModel): """ @@ -37,53 +38,27 @@ class AdditionalPropertiesClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "map_property": obj.get("map_property"), - "map_of_map_property": obj.get("map_of_map_property") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_object.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_object.py index 00707c3c4818..4484e38c8bef 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_object.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesObject(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_with_description_only.py index d8049b519ed0..0dd3de45f5d3 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_with_description_only.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/additional_properties_with_description_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesWithDescriptionOnly(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesWithDescriptionOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesWithDescriptionOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/all_of_super_model.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/all_of_super_model.py index 03f554592935..ed486fe11505 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/all_of_super_model.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/all_of_super_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AllOfSuperModel(BaseModel): """ @@ -36,52 +37,27 @@ class AllOfSuperModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AllOfSuperModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AllOfSuperModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/all_of_with_single_ref.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/all_of_with_single_ref.py index 44c7da9114a8..bffacd075374 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/all_of_with_single_ref.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/all_of_with_single_ref.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.single_ref_type import SingleRefType from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AllOfWithSingleRef(BaseModel): """ @@ -38,53 +39,27 @@ class AllOfWithSingleRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AllOfWithSingleRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AllOfWithSingleRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "username": obj.get("username"), - "SingleRefType": obj.get("SingleRefType") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/animal.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/animal.py index 56bec73a9ccd..6af4a155d46a 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/animal.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/animal.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -60,52 +61,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Union[Cat, Dog]]: - """Create an instance of Animal from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[Cat, Dog]]: - """Create an instance of Animal from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'Cat': - return import_module("petstore_api.models.cat").Cat.from_dict(obj) - if object_type == 'Dog': - return import_module("petstore_api.models.dog").Dog.from_dict(obj) - - raise ValueError("Animal failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_color.py index f6d277e79498..b86b03be3591 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_color.py @@ -13,8 +13,6 @@ from __future__ import annotations -from inspect import getfullargspec -import json import pprint import re # noqa: F401 from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator @@ -22,135 +20,56 @@ from typing_extensions import Annotated from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self -from pydantic import Field +from pydantic import Field, RootModel ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] -class AnyOfColor(BaseModel): + +class AnyOfColor(RootModel[Union[List[int], str]]): """ Any of RGB array, RGBA array, or hex string. """ - # data type: List[int] - anyof_schema_1_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=3, max_length=3)]] = Field(default=None, description="RGB three element array with values 0-255.") - # data type: List[int] - anyof_schema_2_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=4, max_length=4)]] = Field(default=None, description="RGBA four element array with values 0-255.") - # data type: str - anyof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") - if TYPE_CHECKING: - actual_instance: Optional[Union[List[int], str]] = None - else: - actual_instance: Any = None - any_of_schemas: Set[str] = { "List[int]", "str" } - - model_config = { - "validate_assignment": True, - "protected_namespaces": (), - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - instance = AnyOfColor.model_construct() - error_messages = [] - # validate data type: List[int] - try: - instance.anyof_schema_1_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: List[int] - try: - instance.anyof_schema_2_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.anyof_schema_3_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return v + root: Union[List[int], str] = Field( + ... + ) + + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ + + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod def from_dict(cls, obj: Dict[str, Any]) -> Self: - return cls.from_json(json.dumps(obj)) + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - # deserialize data into List[int] - try: - # validation - instance.anyof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_1_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into List[int] - try: - # validation - instance.anyof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_2_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.anyof_schema_3_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_3_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) + return self.model_dump_json(by_alias=True, exclude_none=True) - def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) + diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_pig.py index c949e136f415..a632d3c382d6 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/any_of_pig.py @@ -13,8 +13,6 @@ from __future__ import annotations -from inspect import getfullargspec -import json import pprint import re # noqa: F401 from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator @@ -23,112 +21,56 @@ from petstore_api.models.danish_pig import DanishPig from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self -from pydantic import Field +from pydantic import Field, RootModel ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] -class AnyOfPig(BaseModel): + +class AnyOfPig(RootModel[Union[BasquePig, DanishPig]]): """ AnyOfPig """ - # data type: BasquePig - anyof_schema_1_validator: Optional[BasquePig] = None - # data type: DanishPig - anyof_schema_2_validator: Optional[DanishPig] = None - if TYPE_CHECKING: - actual_instance: Optional[Union[BasquePig, DanishPig]] = None - else: - actual_instance: Any = None - any_of_schemas: Set[str] = { "BasquePig", "DanishPig" } - - model_config = { - "validate_assignment": True, - "protected_namespaces": (), - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - instance = AnyOfPig.model_construct() - error_messages = [] - # validate data type: BasquePig - if not isinstance(v, BasquePig): - error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`") - else: - return v - - # validate data type: DanishPig - if not isinstance(v, DanishPig): - error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`") - else: - return v - - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return v + root: Union[BasquePig, DanishPig] = Field( + ... + ) + + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ + + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod def from_dict(cls, obj: Dict[str, Any]) -> Self: - return cls.from_json(json.dumps(obj)) + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - # anyof_schema_1_validator: Optional[BasquePig] = None - try: - instance.actual_instance = BasquePig.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # anyof_schema_2_validator: Optional[DanishPig] = None - try: - instance.actual_instance = DanishPig.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) + return self.model_dump_json(by_alias=True, exclude_none=True) - def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) + diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_array_of_model.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_array_of_model.py index 4f8eeda66c30..7213f2a1cad9 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_array_of_model.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfArrayOfModel(BaseModel): """ @@ -37,64 +38,27 @@ class ArrayOfArrayOfModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in another_property (list of list) - _items = [] - if self.another_property: - for _item_another_property in self.another_property: - if _item_another_property: - _items.append( - [_inner_item.to_dict() for _inner_item in _item_another_property if _inner_item is not None] - ) - _dict['another_property'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "another_property": [ - [Tag.from_dict(_inner_item) for _inner_item in _item] - for _item in obj["another_property"] - ] if obj.get("another_property") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_array_of_number_only.py index 02b0f6d657f4..e477a9006153 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_array_of_number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfArrayOfNumberOnly(BaseModel): """ @@ -36,52 +37,27 @@ class ArrayOfArrayOfNumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfNumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfNumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "ArrayArrayNumber": obj.get("ArrayArrayNumber") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_number_only.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_number_only.py index b22632b0ce4d..692a8662c7b5 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_of_number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfNumberOnly(BaseModel): """ @@ -36,52 +37,27 @@ class ArrayOfNumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfNumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfNumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "ArrayNumber": obj.get("ArrayNumber") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_test.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_test.py index e8f8acf67cc0..c8b3e175de72 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_test.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/array_test.py @@ -22,7 +22,8 @@ from typing_extensions import Annotated from petstore_api.models.read_only_first import ReadOnlyFirst from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayTest(BaseModel): """ @@ -41,67 +42,27 @@ class ArrayTest(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in array_array_of_model (list of list) - _items = [] - if self.array_array_of_model: - for _item_array_array_of_model in self.array_array_of_model: - if _item_array_array_of_model: - _items.append( - [_inner_item.to_dict() for _inner_item in _item_array_array_of_model if _inner_item is not None] - ) - _dict['array_array_of_model'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "array_of_string": obj.get("array_of_string"), - "array_of_nullable_float": obj.get("array_of_nullable_float"), - "array_array_of_integer": obj.get("array_array_of_integer"), - "array_array_of_model": [ - [ReadOnlyFirst.from_dict(_inner_item) for _inner_item in _item] - for _item in obj["array_array_of_model"] - ] if obj.get("array_array_of_model") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/base_discriminator.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/base_discriminator.py index f13c270b56b5..6946039d34d2 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/base_discriminator.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/base_discriminator.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -59,52 +60,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Union[PrimitiveString, Info]]: - """Create an instance of BaseDiscriminator from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[PrimitiveString, Info]]: - """Create an instance of BaseDiscriminator from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'PrimitiveString': - return import_module("petstore_api.models.primitive_string").PrimitiveString.from_dict(obj) - if object_type == 'Info': - return import_module("petstore_api.models.info").Info.from_dict(obj) - - raise ValueError("BaseDiscriminator failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/basque_pig.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/basque_pig.py index a1f32a6edcfc..cc3c77e89471 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/basque_pig.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/basque_pig.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class BasquePig(BaseModel): """ @@ -37,53 +38,27 @@ class BasquePig(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of BasquePig from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of BasquePig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/bathing.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/bathing.py index 088e6ad3b873..8b376f1c1ac1 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/bathing.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/bathing.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Bathing(BaseModel): """ Bathing """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning_deep'] = Field( + ..., + description="task_name of the Bathing", + alias="task_name" + ) + function_name: Literal['care_nourish'] = Field( + ..., + description="function_name of the Bathing", + alias="function_name" + ) content: StrictStr __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -52,54 +61,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Bathing from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Bathing from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/capitalization.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/capitalization.py index b3c20af54440..cf44f6a8d7ff 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/capitalization.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/capitalization.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Capitalization(BaseModel): """ @@ -41,57 +42,27 @@ class Capitalization(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Capitalization from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Capitalization from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "smallCamel": obj.get("smallCamel"), - "CapitalCamel": obj.get("CapitalCamel"), - "small_Snake": obj.get("small_Snake"), - "Capital_Snake": obj.get("Capital_Snake"), - "SCA_ETH_Flow_Points": obj.get("SCA_ETH_Flow_Points"), - "ATT_NAME": obj.get("ATT_NAME") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/cat.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/cat.py index 0c2c9788dca3..dd9ba455914c 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/cat.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/cat.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Cat(Animal): """ @@ -37,54 +38,27 @@ class Cat(Animal): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Cat from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Cat from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") if obj.get("color") is not None else 'red', - "declawed": obj.get("declawed") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/category.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/category.py index dcc6247b5ac7..3b46a4d7e44e 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/category.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/category.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Category(BaseModel): """ @@ -37,53 +38,27 @@ class Category(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Category from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Category from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") if obj.get("name") is not None else 'default-name' - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/circular_all_of_ref.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/circular_all_of_ref.py index f98247ae0fb5..f3525d486eee 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/circular_all_of_ref.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/circular_all_of_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CircularAllOfRef(BaseModel): """ @@ -37,61 +38,28 @@ class CircularAllOfRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CircularAllOfRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in second_circular_all_of_ref (list) - _items = [] - if self.second_circular_all_of_ref: - for _item_second_circular_all_of_ref in self.second_circular_all_of_ref: - if _item_second_circular_all_of_ref: - _items.append(_item_second_circular_all_of_ref.to_dict()) - _dict['secondCircularAllOfRef'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CircularAllOfRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name"), - "secondCircularAllOfRef": [SecondCircularAllOfRef.from_dict(_item) for _item in obj["secondCircularAllOfRef"]] if obj.get("secondCircularAllOfRef") is not None else None - }) - return _obj from petstore_api.models.second_circular_all_of_ref import SecondCircularAllOfRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/circular_reference_model.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/circular_reference_model.py index 3b2854caaac2..51a3cf9107a7 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/circular_reference_model.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/circular_reference_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CircularReferenceModel(BaseModel): """ @@ -37,57 +38,28 @@ class CircularReferenceModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CircularReferenceModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested - if self.nested: - _dict['nested'] = self.nested.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CircularReferenceModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested": FirstRef.from_dict(obj["nested"]) if obj.get("nested") is not None else None - }) - return _obj from petstore_api.models.first_ref import FirstRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/class_model.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/class_model.py index 6def0e52d146..6988fc984136 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/class_model.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/class_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ClassModel(BaseModel): """ @@ -36,52 +37,27 @@ class ClassModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ClassModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ClassModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_class": obj.get("_class") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/client.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/client.py index 1c12c9a145c8..f7b9f517226d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/client.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/client.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Client(BaseModel): """ @@ -36,52 +37,27 @@ class Client(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Client from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Client from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "client": obj.get("client") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/color.py index bb740fb597d4..5197fe58ecc6 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/color.py @@ -18,150 +18,55 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional from typing_extensions import Annotated -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] -class Color(BaseModel): +class Color(RootModel[Union[List[int], str]]): """ RGB array, RGBA array, or hex string. """ - # data type: List[int] - oneof_schema_1_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=3, max_length=3)]] = Field(default=None, description="RGB three element array with values 0-255.") - # data type: List[int] - oneof_schema_2_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=4, max_length=4)]] = Field(default=None, description="RGBA four element array with values 0-255.") - # data type: str - oneof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") - actual_instance: Optional[Union[List[int], str]] = None - one_of_schemas: Set[str] = { "List[int]", "str" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[List[int], str, None] = Field( + None ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - if v is None: - return v - - instance = Color.model_construct() - error_messages = [] - match = 0 - # validate data type: List[int] - try: - instance.oneof_schema_1_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: List[int] - try: - instance.oneof_schema_2_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.oneof_schema_3_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: Optional[str]) -> Self: + def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - if json_str is None: - return instance - - error_messages = [] - match = 0 - - # deserialize data into List[int] - try: - # validation - instance.oneof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_1_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into List[int] - try: - # validation - instance.oneof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_2_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.oneof_schema_3_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_3_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/creature.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/creature.py index 2ed3aa42bf99..f4509fd781b3 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/creature.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/creature.py @@ -22,7 +22,8 @@ from typing import Any, ClassVar, Dict, List, Union from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -60,53 +61,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[HuntingDog]]: - """Create an instance of Creature from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of info - if self.info: - _dict['info'] = self.info.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[HuntingDog]]: - """Create an instance of Creature from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'HuntingDog': - return import_module("petstore_api.models.hunting_dog").HuntingDog.from_dict(obj) - - raise ValueError("Creature failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/creature_info.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/creature_info.py index e7927446c238..46da1157c838 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/creature_info.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/creature_info.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CreatureInfo(BaseModel): """ @@ -36,52 +37,27 @@ class CreatureInfo(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CreatureInfo from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CreatureInfo from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/danish_pig.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/danish_pig.py index 061e16a486a5..d8dda939f40e 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/danish_pig.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/danish_pig.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DanishPig(BaseModel): """ @@ -37,53 +38,27 @@ class DanishPig(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DanishPig from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DanishPig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "size": obj.get("size") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/deprecated_object.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/deprecated_object.py index bb4747a1e18c..225295ec6a18 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/deprecated_object.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/deprecated_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DeprecatedObject(BaseModel): """ @@ -36,52 +37,27 @@ class DeprecatedObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DeprecatedObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DeprecatedObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/discriminator_all_of_sub.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/discriminator_all_of_sub.py index 2e8d4a6d7633..e488c3d8a0ba 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/discriminator_all_of_sub.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/discriminator_all_of_sub.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List from petstore_api.models.discriminator_all_of_super import DiscriminatorAllOfSuper from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DiscriminatorAllOfSub(DiscriminatorAllOfSuper): """ @@ -36,52 +37,27 @@ class DiscriminatorAllOfSub(DiscriminatorAllOfSuper): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DiscriminatorAllOfSub from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DiscriminatorAllOfSub from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "elementType": obj.get("elementType") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/discriminator_all_of_super.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/discriminator_all_of_super.py index ee910f90ea69..476d44bbb9b0 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/discriminator_all_of_super.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/discriminator_all_of_super.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -58,50 +59,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Union[DiscriminatorAllOfSub]]: - """Create an instance of DiscriminatorAllOfSuper from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[DiscriminatorAllOfSub]]: - """Create an instance of DiscriminatorAllOfSuper from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'DiscriminatorAllOfSub': - return import_module("petstore_api.models.discriminator_all_of_sub").DiscriminatorAllOfSub.from_dict(obj) - - raise ValueError("DiscriminatorAllOfSuper failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/dog.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/dog.py index a0f4ed786b4e..1cdf9778bb2d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/dog.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/dog.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Dog(Animal): """ @@ -37,54 +38,27 @@ class Dog(Animal): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Dog from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Dog from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") if obj.get("color") is not None else 'red', - "breed": obj.get("breed") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/dummy_model.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/dummy_model.py index 3050cbf66dc4..230684d30487 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/dummy_model.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/dummy_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DummyModel(BaseModel): """ @@ -37,57 +38,28 @@ class DummyModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DummyModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of self_ref - if self.self_ref: - _dict['self_ref'] = self.self_ref.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DummyModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "self_ref": SelfReferenceModel.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None - }) - return _obj from petstore_api.models.self_reference_model import SelfReferenceModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_arrays.py index 68ceb962b03e..2ffde2d8e823 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_arrays.py @@ -20,14 +20,21 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumArrays(BaseModel): """ EnumArrays """ # noqa: E501 - just_symbol: Optional[StrictStr] = None - array_enum: Optional[List[StrictStr]] = None + just_symbol: Optional[Literal['>=', '$']] = Field( + None, + description="just_symbol of the EnumArrays" + ) + array_enum: Optional[List[Literal['fish', 'crab']]] = Field( + None, + description="array_enum of the EnumArrays" + ) __properties: ClassVar[List[str]] = ["just_symbol", "array_enum"] @field_validator('just_symbol') @@ -58,53 +65,27 @@ def array_enum_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumArrays from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumArrays from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "just_symbol": obj.get("just_symbol"), - "array_enum": obj.get("array_enum") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_ref_with_default_value.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_ref_with_default_value.py index 9d97e3fd16d4..0f238270fd0c 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_ref_with_default_value.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_ref_with_default_value.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.data_output_format import DataOutputFormat from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumRefWithDefaultValue(BaseModel): """ @@ -37,52 +38,27 @@ class EnumRefWithDefaultValue(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumRefWithDefaultValue from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumRefWithDefaultValue from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "report_format": obj.get("report_format") if obj.get("report_format") is not None else DataOutputFormat.JSON - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_test.py index b7e6ec36230f..d59763c5a82d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/enum_test.py @@ -26,19 +26,43 @@ from petstore_api.models.outer_enum_integer import OuterEnumInteger from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumTest(BaseModel): """ EnumTest """ # noqa: E501 - enum_string: Optional[StrictStr] = None - enum_string_required: StrictStr - enum_integer_default: Optional[StrictInt] = 5 - enum_integer: Optional[StrictInt] = None - enum_number: Optional[float] = None - enum_string_single_member: Optional[StrictStr] = None - enum_integer_single_member: Optional[StrictInt] = None + enum_string: Optional[Literal['UPPER', 'lower', '']] = Field( + None, + description="enum_string of the EnumTest" + ) + enum_string_required: Literal['UPPER', 'lower', ''] = Field( + ..., + description="enum_string_required of the EnumTest" + ) + enum_integer_default: Optional[Literal[1, 5, 14]] = Field( + None, + description="enum_integer_default of the EnumTest" + ) + enum_integer: Optional[Literal[1, -1]] = Field( + None, + description="enum_integer of the EnumTest" + ) + enum_number: Optional[Literal[1.1, -1.2]] = Field( + None, + description="enum_number of the EnumTest" + ) + enum_string_single_member: Literal['abc'] = Field( + None, + description="enum_string_single_member of the EnumTest", + alias="enum_string_single_member" + ) + enum_integer_single_member: Literal['100'] = Field( + None, + description="enum_integer_single_member of the EnumTest", + alias="enum_integer_single_member" + ) outer_enum: Optional[OuterEnum] = Field(default=None, alias="outerEnum") outer_enum_integer: Optional[OuterEnumInteger] = Field(default=None, alias="outerEnumInteger") outer_enum_default_value: Optional[OuterEnumDefaultValue] = Field(default=OuterEnumDefaultValue.PLACED, alias="outerEnumDefaultValue") @@ -121,69 +145,27 @@ def enum_integer_single_member_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if outer_enum (nullable) is None - # and model_fields_set contains the field - if self.outer_enum is None and "outer_enum" in self.model_fields_set: - _dict['outerEnum'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "enum_string": obj.get("enum_string"), - "enum_string_required": obj.get("enum_string_required"), - "enum_integer_default": obj.get("enum_integer_default") if obj.get("enum_integer_default") is not None else 5, - "enum_integer": obj.get("enum_integer"), - "enum_number": obj.get("enum_number"), - "enum_string_single_member": obj.get("enum_string_single_member"), - "enum_integer_single_member": obj.get("enum_integer_single_member"), - "outerEnum": obj.get("outerEnum"), - "outerEnumInteger": obj.get("outerEnumInteger"), - "outerEnumDefaultValue": obj.get("outerEnumDefaultValue") if obj.get("outerEnumDefaultValue") is not None else OuterEnumDefaultValue.PLACED, - "outerEnumIntegerDefaultValue": obj.get("outerEnumIntegerDefaultValue") if obj.get("outerEnumIntegerDefaultValue") is not None else OuterEnumIntegerDefaultValue.NUMBER_0, - "enumNumberVendorExt": obj.get("enumNumberVendorExt"), - "enumStringVendorExt": obj.get("enumStringVendorExt") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/feeding.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/feeding.py index 1183b314fdd0..1f6ff4555236 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/feeding.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/feeding.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Feeding(BaseModel): """ Feeding """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning'] = Field( + ..., + description="task_name of the Feeding", + alias="task_name" + ) + function_name: Literal['care_nourish'] = Field( + ..., + description="function_name of the Feeding", + alias="function_name" + ) content: StrictStr __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -52,54 +61,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Feeding from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Feeding from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/file.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/file.py index 0ecacf44bb8e..213a82e08c80 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/file.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/file.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class File(BaseModel): """ @@ -36,52 +37,27 @@ class File(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of File from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of File from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "sourceURI": obj.get("sourceURI") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/file_schema_test_class.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/file_schema_test_class.py index c533c0777b24..7fe7d4e48409 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/file_schema_test_class.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.file import File from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FileSchemaTestClass(BaseModel): """ @@ -38,63 +39,27 @@ class FileSchemaTestClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FileSchemaTestClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of file - if self.file: - _dict['file'] = self.file.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in files (list) - _items = [] - if self.files: - for _item_files in self.files: - if _item_files: - _items.append(_item_files.to_dict()) - _dict['files'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FileSchemaTestClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "file": File.from_dict(obj["file"]) if obj.get("file") is not None else None, - "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/first_ref.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/first_ref.py index 6aa0f722d874..77fba27b8ba3 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/first_ref.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/first_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FirstRef(BaseModel): """ @@ -37,57 +38,28 @@ class FirstRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FirstRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of self_ref - if self.self_ref: - _dict['self_ref'] = self.self_ref.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FirstRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "self_ref": SecondRef.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None - }) - return _obj from petstore_api.models.second_ref import SecondRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/foo.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/foo.py index 67b29f1ab87c..902c6ccbb7f6 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/foo.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/foo.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Foo(BaseModel): """ @@ -36,52 +37,27 @@ class Foo(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Foo from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Foo from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar") if obj.get("bar") is not None else 'bar' - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/foo_get_default_response.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/foo_get_default_response.py index ae191aad80a8..51b1e9d1a1ed 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/foo_get_default_response.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/foo_get_default_response.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.foo import Foo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FooGetDefaultResponse(BaseModel): """ @@ -37,55 +38,27 @@ class FooGetDefaultResponse(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FooGetDefaultResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of string - if self.string: - _dict['string'] = self.string.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FooGetDefaultResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "string": Foo.from_dict(obj["string"]) if obj.get("string") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/format_test.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/format_test.py index 8d70a96f3a7c..dd2537299ef2 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/format_test.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/format_test.py @@ -24,7 +24,8 @@ from typing_extensions import Annotated from uuid import UUID from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FormatTest(BaseModel): """ @@ -96,68 +97,27 @@ def pattern_with_digits_and_delimiter_validate_regular_expression(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FormatTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FormatTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "integer": obj.get("integer"), - "int32": obj.get("int32"), - "int64": obj.get("int64"), - "number": obj.get("number"), - "float": obj.get("float"), - "double": obj.get("double"), - "decimal": obj.get("decimal"), - "string": obj.get("string"), - "string_with_double_quote_pattern": obj.get("string_with_double_quote_pattern"), - "byte": obj.get("byte"), - "binary": obj.get("binary"), - "date": obj.get("date"), - "dateTime": obj.get("dateTime"), - "uuid": obj.get("uuid"), - "password": obj.get("password"), - "pattern_with_digits": obj.get("pattern_with_digits"), - "pattern_with_digits_and_delimiter": obj.get("pattern_with_digits_and_delimiter") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/has_only_read_only.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/has_only_read_only.py index 2137bc880484..f0721e724492 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/has_only_read_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HasOnlyReadOnly(BaseModel): """ @@ -37,57 +38,27 @@ class HasOnlyReadOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HasOnlyReadOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * OpenAPI `readOnly` fields are excluded. - """ - excluded_fields: Set[str] = set([ - "bar", - "foo", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HasOnlyReadOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar"), - "foo": obj.get("foo") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/health_check_result.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/health_check_result.py index 4dbdd852097f..007ebd7c3fba 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/health_check_result.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/health_check_result.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HealthCheckResult(BaseModel): """ @@ -36,57 +37,27 @@ class HealthCheckResult(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HealthCheckResult from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if nullable_message (nullable) is None - # and model_fields_set contains the field - if self.nullable_message is None and "nullable_message" in self.model_fields_set: - _dict['NullableMessage'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HealthCheckResult from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "NullableMessage": obj.get("NullableMessage") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/hunting_dog.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/hunting_dog.py index cd678616f62f..0bd4255928fb 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/hunting_dog.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/hunting_dog.py @@ -22,7 +22,8 @@ from petstore_api.models.creature import Creature from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HuntingDog(Creature): """ @@ -38,57 +39,27 @@ class HuntingDog(Creature): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HuntingDog from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of info - if self.info: - _dict['info'] = self.info.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HuntingDog from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "info": CreatureInfo.from_dict(obj["info"]) if obj.get("info") is not None else None, - "type": obj.get("type"), - "isTrained": obj.get("isTrained") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/info.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/info.py index 5a15b5f9f52f..da9fc38935f9 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/info.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/info.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.base_discriminator import BaseDiscriminator from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Info(BaseDiscriminator): """ @@ -37,56 +38,27 @@ class Info(BaseDiscriminator): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Info from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of val - if self.val: - _dict['val'] = self.val.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Info from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_typeName": obj.get("_typeName"), - "val": BaseDiscriminator.from_dict(obj["val"]) if obj.get("val") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/inner_dict_with_property.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/inner_dict_with_property.py index 27816b995f53..8c1f33db2d78 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/inner_dict_with_property.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/inner_dict_with_property.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class InnerDictWithProperty(BaseModel): """ @@ -36,52 +37,27 @@ class InnerDictWithProperty(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of InnerDictWithProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of InnerDictWithProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "aProperty": obj.get("aProperty") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/input_all_of.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/input_all_of.py index 63870cca83ed..9c3716d502b0 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/input_all_of.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/input_all_of.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class InputAllOf(BaseModel): """ @@ -37,64 +38,27 @@ class InputAllOf(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of InputAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in some_data (dict) - _field_dict = {} - if self.some_data: - for _key_some_data in self.some_data: - if self.some_data[_key_some_data]: - _field_dict[_key_some_data] = self.some_data[_key_some_data].to_dict() - _dict['some_data'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of InputAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "some_data": dict( - (_k, Tag.from_dict(_v)) - for _k, _v in obj["some_data"].items() - ) - if obj.get("some_data") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..c66bf1ab9772 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/int_or_string.py @@ -18,127 +18,55 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional from typing_extensions import Annotated -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] -class IntOrString(BaseModel): +class IntOrString(RootModel[Union[int, str]]): """ IntOrString """ - # data type: int - oneof_schema_1_validator: Optional[Annotated[int, Field(strict=True, ge=10)]] = None - # data type: str - oneof_schema_2_validator: Optional[StrictStr] = None - actual_instance: Optional[Union[int, str]] = None - one_of_schemas: Set[str] = { "int", "str" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[int, str] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = IntOrString.model_construct() - error_messages = [] - match = 0 - # validate data type: int - try: - instance.oneof_schema_1_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.oneof_schema_2_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into int - try: - # validation - instance.oneof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_1_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.oneof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_2_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/list_class.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/list_class.py index ab12a7fac521..be0a9543d04d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/list_class.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/list_class.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ListClass(BaseModel): """ @@ -36,52 +37,27 @@ class ListClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ListClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ListClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "123-list": obj.get("123-list") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/map_of_array_of_model.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/map_of_array_of_model.py index a9bd000ad9ba..5ed090e91592 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/map_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/map_of_array_of_model.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MapOfArrayOfModel(BaseModel): """ @@ -37,68 +38,27 @@ class MapOfArrayOfModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MapOfArrayOfModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in shop_id_to_org_online_lip_map (dict of array) - _field_dict_of_array = {} - if self.shop_id_to_org_online_lip_map: - for _key_shop_id_to_org_online_lip_map in self.shop_id_to_org_online_lip_map: - if self.shop_id_to_org_online_lip_map[_key_shop_id_to_org_online_lip_map] is not None: - _field_dict_of_array[_key_shop_id_to_org_online_lip_map] = [ - _item.to_dict() for _item in self.shop_id_to_org_online_lip_map[_key_shop_id_to_org_online_lip_map] - ] - _dict['shopIdToOrgOnlineLipMap'] = _field_dict_of_array - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MapOfArrayOfModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "shopIdToOrgOnlineLipMap": dict( - (_k, - [Tag.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("shopIdToOrgOnlineLipMap", {}).items() - ) - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/map_test.py index 2a056ab5532a..05677731440d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/map_test.py @@ -20,14 +20,18 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MapTest(BaseModel): """ MapTest """ # noqa: E501 map_map_of_string: Optional[Dict[str, Dict[str, StrictStr]]] = None - map_of_enum_string: Optional[Dict[str, StrictStr]] = None + map_of_enum_string: Optional[Literal['UPPER', 'lower']] = Field( + None, + description="map_of_enum_string of the MapTest" + ) direct_map: Optional[Dict[str, StrictBool]] = None indirect_map: Optional[Dict[str, StrictBool]] = None __properties: ClassVar[List[str]] = ["map_map_of_string", "map_of_enum_string", "direct_map", "indirect_map"] @@ -50,55 +54,27 @@ def map_of_enum_string_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MapTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MapTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "map_map_of_string": obj.get("map_map_of_string"), - "map_of_enum_string": obj.get("map_of_enum_string"), - "direct_map": obj.get("direct_map"), - "indirect_map": obj.get("indirect_map") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/mixed_properties_and_additional_properties_class.py index 46998dfb5c68..141ee7f93eb0 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -23,7 +23,8 @@ from uuid import UUID from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): """ @@ -41,66 +42,27 @@ class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in map (dict) - _field_dict = {} - if self.map: - for _key_map in self.map: - if self.map[_key_map]: - _field_dict[_key_map] = self.map[_key_map].to_dict() - _dict['map'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "uuid": obj.get("uuid"), - "dateTime": obj.get("dateTime"), - "map": dict( - (_k, Animal.from_dict(_v)) - for _k, _v in obj["map"].items() - ) - if obj.get("map") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model200_response.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model200_response.py index d6012c57fbd7..8466c296265f 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model200_response.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model200_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Model200Response(BaseModel): """ @@ -37,53 +38,27 @@ class Model200Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Model200Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Model200Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name"), - "class": obj.get("class") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_api_response.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_api_response.py index 005c77823bef..7c9a05eb1df9 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_api_response.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_api_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelApiResponse(BaseModel): """ @@ -38,54 +39,27 @@ class ModelApiResponse(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelApiResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelApiResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "code": obj.get("code"), - "type": obj.get("type"), - "message": obj.get("message") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_field.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_field.py index 9e36a6ac7e48..ab4c4b0c1102 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_field.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_field.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelField(BaseModel): """ @@ -36,52 +37,27 @@ class ModelField(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelField from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelField from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "field": obj.get("field") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_return.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_return.py index a8c0f53f6c19..41a8af9a1a6d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_return.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/model_return.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelReturn(BaseModel): """ @@ -36,52 +37,27 @@ class ModelReturn(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelReturn from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelReturn from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "return": obj.get("return") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/multi_arrays.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/multi_arrays.py index 177a8359468f..2bdb5ddfeb4e 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/multi_arrays.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/multi_arrays.py @@ -22,7 +22,8 @@ from petstore_api.models.file import File from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MultiArrays(BaseModel): """ @@ -39,67 +40,27 @@ class MultiArrays(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MultiArrays from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - # override the default output from pydantic by calling `to_dict()` of each item in files (list) - _items = [] - if self.files: - for _item_files in self.files: - if _item_files: - _items.append(_item_files.to_dict()) - _dict['files'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MultiArrays from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/name.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/name.py index f33b2ecb18be..0c6efd791f89 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/name.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/name.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Name(BaseModel): """ @@ -39,59 +40,27 @@ class Name(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Name from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * OpenAPI `readOnly` fields are excluded. - """ - excluded_fields: Set[str] = set([ - "snake_case", - "var_123_number", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Name from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name"), - "snake_case": obj.get("snake_case"), - "property": obj.get("property"), - "123Number": obj.get("123Number") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nullable_class.py index 9d1414954830..d1780fadb477 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nullable_class.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NullableClass(BaseModel): """ @@ -50,131 +51,27 @@ class NullableClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NullableClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if required_integer_prop (nullable) is None - # and model_fields_set contains the field - if self.required_integer_prop is None and "required_integer_prop" in self.model_fields_set: - _dict['required_integer_prop'] = None - - # set to None if integer_prop (nullable) is None - # and model_fields_set contains the field - if self.integer_prop is None and "integer_prop" in self.model_fields_set: - _dict['integer_prop'] = None - - # set to None if number_prop (nullable) is None - # and model_fields_set contains the field - if self.number_prop is None and "number_prop" in self.model_fields_set: - _dict['number_prop'] = None - - # set to None if boolean_prop (nullable) is None - # and model_fields_set contains the field - if self.boolean_prop is None and "boolean_prop" in self.model_fields_set: - _dict['boolean_prop'] = None - - # set to None if string_prop (nullable) is None - # and model_fields_set contains the field - if self.string_prop is None and "string_prop" in self.model_fields_set: - _dict['string_prop'] = None - - # set to None if date_prop (nullable) is None - # and model_fields_set contains the field - if self.date_prop is None and "date_prop" in self.model_fields_set: - _dict['date_prop'] = None - - # set to None if datetime_prop (nullable) is None - # and model_fields_set contains the field - if self.datetime_prop is None and "datetime_prop" in self.model_fields_set: - _dict['datetime_prop'] = None - - # set to None if array_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.array_nullable_prop is None and "array_nullable_prop" in self.model_fields_set: - _dict['array_nullable_prop'] = None - - # set to None if array_and_items_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.array_and_items_nullable_prop is None and "array_and_items_nullable_prop" in self.model_fields_set: - _dict['array_and_items_nullable_prop'] = None - - # set to None if object_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.object_nullable_prop is None and "object_nullable_prop" in self.model_fields_set: - _dict['object_nullable_prop'] = None - - # set to None if object_and_items_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.object_and_items_nullable_prop is None and "object_and_items_nullable_prop" in self.model_fields_set: - _dict['object_and_items_nullable_prop'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NullableClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "required_integer_prop": obj.get("required_integer_prop"), - "integer_prop": obj.get("integer_prop"), - "number_prop": obj.get("number_prop"), - "boolean_prop": obj.get("boolean_prop"), - "string_prop": obj.get("string_prop"), - "date_prop": obj.get("date_prop"), - "datetime_prop": obj.get("datetime_prop"), - "array_nullable_prop": obj.get("array_nullable_prop"), - "array_and_items_nullable_prop": obj.get("array_and_items_nullable_prop"), - "array_items_nullable": obj.get("array_items_nullable"), - "object_nullable_prop": obj.get("object_nullable_prop"), - "object_and_items_nullable_prop": obj.get("object_and_items_nullable_prop"), - "object_items_nullable": obj.get("object_items_nullable") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nullable_property.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nullable_property.py index 2324745d7dd1..910b6cd762ae 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nullable_property.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/nullable_property.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NullableProperty(BaseModel): """ @@ -48,58 +49,27 @@ def name_validate_regular_expression(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NullableProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if name (nullable) is None - # and model_fields_set contains the field - if self.name is None and "name" in self.model_fields_set: - _dict['name'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NullableProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/number_only.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/number_only.py index 18c3ec953080..3dc8a40ea29a 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/number_only.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NumberOnly(BaseModel): """ @@ -36,52 +37,27 @@ class NumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "JustNumber": obj.get("JustNumber") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/object_to_test_additional_properties.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/object_to_test_additional_properties.py index 22b8bd401a1c..d8e224dbfeda 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/object_to_test_additional_properties.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/object_to_test_additional_properties.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ObjectToTestAdditionalProperties(BaseModel): """ @@ -36,52 +37,27 @@ class ObjectToTestAdditionalProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ObjectToTestAdditionalProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ObjectToTestAdditionalProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "property": obj.get("property") if obj.get("property") is not None else False - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/object_with_deprecated_fields.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/object_with_deprecated_fields.py index 4d76d9f5fc72..41dfcf6f1019 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/object_with_deprecated_fields.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/object_with_deprecated_fields.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.deprecated_object import DeprecatedObject from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ObjectWithDeprecatedFields(BaseModel): """ @@ -40,58 +41,27 @@ class ObjectWithDeprecatedFields(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ObjectWithDeprecatedFields from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of deprecated_ref - if self.deprecated_ref: - _dict['deprecatedRef'] = self.deprecated_ref.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ObjectWithDeprecatedFields from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "uuid": obj.get("uuid"), - "id": obj.get("id"), - "deprecatedRef": DeprecatedObject.from_dict(obj["deprecatedRef"]) if obj.get("deprecatedRef") is not None else None, - "bars": obj.get("bars") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/order.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/order.py index f742027e088a..8aed7ad5e761 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/order.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Order(BaseModel): """ @@ -31,7 +32,10 @@ class Order(BaseModel): pet_id: Optional[StrictInt] = Field(default=None, alias="petId") quantity: Optional[StrictInt] = None ship_date: Optional[datetime] = Field(default=None, alias="shipDate") - status: Optional[StrictStr] = Field(default=None, description="Order Status") + status: Optional[Literal['placed', 'approved', 'delivered']] = Field( + None, + description="Order Status" + ) complete: Optional[StrictBool] = False __properties: ClassVar[List[str]] = ["id", "petId", "quantity", "shipDate", "status", "complete"] @@ -52,57 +56,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Order from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Order from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "petId": obj.get("petId"), - "quantity": obj.get("quantity"), - "shipDate": obj.get("shipDate"), - "status": obj.get("status"), - "complete": obj.get("complete") if obj.get("complete") is not None else False - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/outer_composite.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/outer_composite.py index 6a82d49970cb..041590afed6c 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/outer_composite.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/outer_composite.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class OuterComposite(BaseModel): """ @@ -38,54 +39,27 @@ class OuterComposite(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of OuterComposite from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of OuterComposite from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "my_number": obj.get("my_number"), - "my_string": obj.get("my_string"), - "my_boolean": obj.get("my_boolean") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/outer_object_with_enum_property.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/outer_object_with_enum_property.py index 4f453c2a8d0c..f53f359d1758 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/outer_object_with_enum_property.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/outer_object_with_enum_property.py @@ -22,7 +22,8 @@ from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_integer import OuterEnumInteger from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class OuterObjectWithEnumProperty(BaseModel): """ @@ -39,58 +40,27 @@ class OuterObjectWithEnumProperty(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of OuterObjectWithEnumProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # set to None if str_value (nullable) is None - # and model_fields_set contains the field - if self.str_value is None and "str_value" in self.model_fields_set: - _dict['str_value'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of OuterObjectWithEnumProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "str_value": obj.get("str_value"), - "value": obj.get("value") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/parent.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/parent.py index 5986da45ab04..4016ba494b38 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/parent.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/parent.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Parent(BaseModel): """ @@ -37,64 +38,27 @@ class Parent(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Parent from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) - _field_dict = {} - if self.optional_dict: - for _key_optional_dict in self.optional_dict: - if self.optional_dict[_key_optional_dict]: - _field_dict[_key_optional_dict] = self.optional_dict[_key_optional_dict].to_dict() - _dict['optionalDict'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Parent from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "optionalDict": dict( - (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj["optionalDict"].items() - ) - if obj.get("optionalDict") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/parent_with_optional_dict.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/parent_with_optional_dict.py index 84445b64043a..513e164538ee 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/parent_with_optional_dict.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/parent_with_optional_dict.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ParentWithOptionalDict(BaseModel): """ @@ -37,64 +38,27 @@ class ParentWithOptionalDict(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ParentWithOptionalDict from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) - _field_dict = {} - if self.optional_dict: - for _key_optional_dict in self.optional_dict: - if self.optional_dict[_key_optional_dict]: - _field_dict[_key_optional_dict] = self.optional_dict[_key_optional_dict].to_dict() - _dict['optionalDict'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ParentWithOptionalDict from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "optionalDict": dict( - (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj["optionalDict"].items() - ) - if obj.get("optionalDict") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pet.py index be47c3b1a894..d399f6ba14aa 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pet.py @@ -23,7 +23,8 @@ from petstore_api.models.category import Category from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Pet(BaseModel): """ @@ -34,7 +35,10 @@ class Pet(BaseModel): name: StrictStr photo_urls: Annotated[List[StrictStr], Field(min_length=0)] = Field(alias="photoUrls") tags: Optional[List[Tag]] = None - status: Optional[StrictStr] = Field(default=None, description="pet status in the store") + status: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) __properties: ClassVar[List[str]] = ["id", "category", "name", "photoUrls", "tags", "status"] @field_validator('status') @@ -54,67 +58,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Pet from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of category - if self.category: - _dict['category'] = self.category.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Pet from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, - "name": obj.get("name"), - "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "status": obj.get("status") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pig.py index b3a759e89b7b..6646e6d477cd 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pig.py @@ -19,122 +19,55 @@ from typing import Any, List, Optional from petstore_api.models.basque_pig import BasquePig from petstore_api.models.danish_pig import DanishPig -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] -class Pig(BaseModel): +class Pig(RootModel[Union[BasquePig, DanishPig]]): """ Pig """ - # data type: BasquePig - oneof_schema_1_validator: Optional[BasquePig] = None - # data type: DanishPig - oneof_schema_2_validator: Optional[DanishPig] = None - actual_instance: Optional[Union[BasquePig, DanishPig]] = None - one_of_schemas: Set[str] = { "BasquePig", "DanishPig" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[BasquePig, DanishPig] = Field( + ..., discriminator="class_name" ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - discriminator_value_class_map: Dict[str, str] = { - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = Pig.model_construct() - error_messages = [] - match = 0 - # validate data type: BasquePig - if not isinstance(v, BasquePig): - error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`") - else: - match += 1 - # validate data type: DanishPig - if not isinstance(v, DanishPig): - error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into BasquePig - try: - instance.actual_instance = BasquePig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DanishPig - try: - instance.actual_instance = DanishPig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pony_sizes.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pony_sizes.py index 00bd38659577..61d969cf2183 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pony_sizes.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/pony_sizes.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.type import Type from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PonySizes(BaseModel): """ @@ -37,52 +38,27 @@ class PonySizes(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PonySizes from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PonySizes from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "type": obj.get("type") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/poop_cleaning.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/poop_cleaning.py index 047cf0d481a9..bd74546967aa 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/poop_cleaning.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/poop_cleaning.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PoopCleaning(BaseModel): """ PoopCleaning """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning'] = Field( + ..., + description="task_name of the PoopCleaning", + alias="task_name" + ) + function_name: Literal['care'] = Field( + ..., + description="function_name of the PoopCleaning", + alias="function_name" + ) content: StrictStr __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -52,54 +61,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PoopCleaning from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PoopCleaning from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/primitive_string.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/primitive_string.py index 5a7065597861..33d2f42d10c4 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/primitive_string.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/primitive_string.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.base_discriminator import BaseDiscriminator from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PrimitiveString(BaseDiscriminator): """ @@ -37,53 +38,27 @@ class PrimitiveString(BaseDiscriminator): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PrimitiveString from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PrimitiveString from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_typeName": obj.get("_typeName"), - "_value": obj.get("_value") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/property_map.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/property_map.py index 940016a86a72..fb4f8fc046c3 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/property_map.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/property_map.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PropertyMap(BaseModel): """ @@ -37,64 +38,27 @@ class PropertyMap(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PropertyMap from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in some_data (dict) - _field_dict = {} - if self.some_data: - for _key_some_data in self.some_data: - if self.some_data[_key_some_data]: - _field_dict[_key_some_data] = self.some_data[_key_some_data].to_dict() - _dict['some_data'] = _field_dict - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PropertyMap from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "some_data": dict( - (_k, Tag.from_dict(_v)) - for _k, _v in obj["some_data"].items() - ) - if obj.get("some_data") is not None - else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/property_name_collision.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/property_name_collision.py index 0eb56422b648..4a65d64d95ac 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/property_name_collision.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/property_name_collision.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PropertyNameCollision(BaseModel): """ @@ -38,54 +39,27 @@ class PropertyNameCollision(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PropertyNameCollision from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PropertyNameCollision from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_type": obj.get("_type"), - "type": obj.get("type"), - "type_": obj.get("type_") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/read_only_first.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/read_only_first.py index c9f4fc6c0df9..5e625cb6d272 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/read_only_first.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/read_only_first.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ReadOnlyFirst(BaseModel): """ @@ -37,55 +38,27 @@ class ReadOnlyFirst(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ReadOnlyFirst from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - """ - excluded_fields: Set[str] = set([ - "bar", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ReadOnlyFirst from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar"), - "baz": obj.get("baz") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/second_circular_all_of_ref.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/second_circular_all_of_ref.py index 854749b4fb13..1d59daedfa70 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/second_circular_all_of_ref.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/second_circular_all_of_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SecondCircularAllOfRef(BaseModel): """ @@ -37,61 +38,28 @@ class SecondCircularAllOfRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SecondCircularAllOfRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in circular_all_of_ref (list) - _items = [] - if self.circular_all_of_ref: - for _item_circular_all_of_ref in self.circular_all_of_ref: - if _item_circular_all_of_ref: - _items.append(_item_circular_all_of_ref.to_dict()) - _dict['circularAllOfRef'] = _items - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SecondCircularAllOfRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name"), - "circularAllOfRef": [CircularAllOfRef.from_dict(_item) for _item in obj["circularAllOfRef"]] if obj.get("circularAllOfRef") is not None else None - }) - return _obj from petstore_api.models.circular_all_of_ref import CircularAllOfRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/second_ref.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/second_ref.py index c6627cf0ba63..68639c27be4e 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/second_ref.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/second_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SecondRef(BaseModel): """ @@ -37,57 +38,28 @@ class SecondRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SecondRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of circular_ref - if self.circular_ref: - _dict['circular_ref'] = self.circular_ref.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SecondRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "circular_ref": CircularReferenceModel.from_dict(obj["circular_ref"]) if obj.get("circular_ref") is not None else None - }) - return _obj from petstore_api.models.circular_reference_model import CircularReferenceModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/self_reference_model.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/self_reference_model.py index 7c145db0d3ae..319aa1bbb7d7 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/self_reference_model.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/self_reference_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SelfReferenceModel(BaseModel): """ @@ -37,57 +38,28 @@ class SelfReferenceModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SelfReferenceModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested - if self.nested: - _dict['nested'] = self.nested.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SelfReferenceModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested": DummyModel.from_dict(obj["nested"]) if obj.get("nested") is not None else None - }) - return _obj from petstore_api.models.dummy_model import DummyModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/special_model_name.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/special_model_name.py index 0336e24d17da..29712f6ce24e 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/special_model_name.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/special_model_name.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SpecialModelName(BaseModel): """ @@ -36,52 +37,27 @@ class SpecialModelName(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SpecialModelName from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SpecialModelName from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "$special[property.name]": obj.get("$special[property.name]") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/special_name.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/special_name.py index d3c8f6185683..36d84e99015d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/special_name.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/special_name.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.category import Category from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SpecialName(BaseModel): """ @@ -29,7 +30,10 @@ class SpecialName(BaseModel): """ # noqa: E501 var_property: Optional[StrictInt] = Field(default=None, alias="property") var_async: Optional[Category] = Field(default=None, alias="async") - var_schema: Optional[StrictStr] = Field(default=None, description="pet status in the store", alias="schema") + var_schema: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) __properties: ClassVar[List[str]] = ["property", "async", "schema"] @field_validator('var_schema') @@ -49,57 +53,27 @@ def var_schema_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SpecialName from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of var_async - if self.var_async: - _dict['async'] = self.var_async.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SpecialName from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "property": obj.get("property"), - "async": Category.from_dict(obj["async"]) if obj.get("async") is not None else None, - "schema": obj.get("schema") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tag.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tag.py index e5ddcbcd4a74..5b2c89ec90a6 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tag.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tag.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tag(BaseModel): """ @@ -37,53 +38,27 @@ class Tag(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tag from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tag from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task.py index 312b2c8ee473..32fdaf499a98 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task.py @@ -22,7 +22,8 @@ from uuid import UUID from petstore_api.models.task_activity import TaskActivity from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Task(BaseModel): """ @@ -39,56 +40,27 @@ class Task(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Task from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of activity - if self.activity: - _dict['activity'] = self.activity.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Task from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "activity": TaskActivity.from_dict(obj["activity"]) if obj.get("activity") is not None else None - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task_activity.py index cc1e1fc5a60f..39a1c0bbc375 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/task_activity.py @@ -20,132 +20,55 @@ from petstore_api.models.bathing import Bathing from petstore_api.models.feeding import Feeding from petstore_api.models.poop_cleaning import PoopCleaning -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] -class TaskActivity(BaseModel): +class TaskActivity(RootModel[Union[Bathing, Feeding, PoopCleaning]]): """ TaskActivity """ - # data type: PoopCleaning - oneof_schema_1_validator: Optional[PoopCleaning] = None - # data type: Feeding - oneof_schema_2_validator: Optional[Feeding] = None - # data type: Bathing - oneof_schema_3_validator: Optional[Bathing] = None - actual_instance: Optional[Union[Bathing, Feeding, PoopCleaning]] = None - one_of_schemas: Set[str] = { "Bathing", "Feeding", "PoopCleaning" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[Bathing, Feeding, PoopCleaning] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = TaskActivity.model_construct() - error_messages = [] - match = 0 - # validate data type: PoopCleaning - if not isinstance(v, PoopCleaning): - error_messages.append(f"Error! Input type `{type(v)}` is not `PoopCleaning`") - else: - match += 1 - # validate data type: Feeding - if not isinstance(v, Feeding): - error_messages.append(f"Error! Input type `{type(v)}` is not `Feeding`") - else: - match += 1 - # validate data type: Bathing - if not isinstance(v, Bathing): - error_messages.append(f"Error! Input type `{type(v)}` is not `Bathing`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into PoopCleaning - try: - instance.actual_instance = PoopCleaning.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into Feeding - try: - instance.actual_instance = Feeding.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into Bathing - try: - instance.actual_instance = Bathing.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_error_responses_with_model400_response.py index cba4ab845e5e..f05c878e947d 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_error_responses_with_model400_response.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_error_responses_with_model400_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestErrorResponsesWithModel400Response(BaseModel): """ @@ -36,52 +37,27 @@ class TestErrorResponsesWithModel400Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel400Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel400Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "reason400": obj.get("reason400") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_error_responses_with_model404_response.py index 787ca11942ab..bf3e78f98b1e 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_error_responses_with_model404_response.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_error_responses_with_model404_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestErrorResponsesWithModel404Response(BaseModel): """ @@ -36,52 +37,27 @@ class TestErrorResponsesWithModel404Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel404Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel404Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "reason404": obj.get("reason404") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_inline_freeform_additional_properties_request.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_inline_freeform_additional_properties_request.py index 7b93d84864f2..83309fd58987 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_inline_freeform_additional_properties_request.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_inline_freeform_additional_properties_request.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): """ @@ -37,64 +38,27 @@ class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "someProperty": obj.get("someProperty") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_model_with_enum_default.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_model_with_enum_default.py index 218fa8f16d22..4b19246316db 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_model_with_enum_default.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_model_with_enum_default.py @@ -22,7 +22,8 @@ from petstore_api.models.test_enum import TestEnum from petstore_api.models.test_enum_with_default import TestEnumWithDefault from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestModelWithEnumDefault(BaseModel): """ @@ -32,7 +33,10 @@ class TestModelWithEnumDefault(BaseModel): test_string: Optional[StrictStr] = None test_enum_with_default: Optional[TestEnumWithDefault] = TestEnumWithDefault.ZWEI test_string_with_default: Optional[StrictStr] = 'ahoy matey' - test_inline_defined_enum_with_default: Optional[StrictStr] = 'B' + test_inline_defined_enum_with_default: Optional[Literal['A', 'B', 'C']] = Field( + None, + description="test_inline_defined_enum_with_default of the TestModelWithEnumDefault" + ) __properties: ClassVar[List[str]] = ["test_enum", "test_string", "test_enum_with_default", "test_string_with_default", "test_inline_defined_enum_with_default"] @field_validator('test_inline_defined_enum_with_default') @@ -52,56 +56,27 @@ def test_inline_defined_enum_with_default_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestModelWithEnumDefault from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestModelWithEnumDefault from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "test_enum": obj.get("test_enum"), - "test_string": obj.get("test_string"), - "test_enum_with_default": obj.get("test_enum_with_default") if obj.get("test_enum_with_default") is not None else TestEnumWithDefault.ZWEI, - "test_string_with_default": obj.get("test_string_with_default") if obj.get("test_string_with_default") is not None else 'ahoy matey', - "test_inline_defined_enum_with_default": obj.get("test_inline_defined_enum_with_default") if obj.get("test_inline_defined_enum_with_default") is not None else 'B' - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_object_for_multipart_requests_request_marker.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_object_for_multipart_requests_request_marker.py index a5c3bfdbb1b5..c736089e90f7 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_object_for_multipart_requests_request_marker.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/test_object_for_multipart_requests_request_marker.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestObjectForMultipartRequestsRequestMarker(BaseModel): """ @@ -36,52 +37,27 @@ class TestObjectForMultipartRequestsRequestMarker(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestObjectForMultipartRequestsRequestMarker from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestObjectForMultipartRequestsRequestMarker from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tiger.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tiger.py index bf8cbf0596ae..70b4af572ae1 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tiger.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/tiger.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tiger(BaseModel): """ @@ -36,52 +37,27 @@ class Tiger(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tiger from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tiger from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "skill": obj.get("skill") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py index e50edf2efa85..4652d2ea4588 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UnnamedDictWithAdditionalModelListProperties(BaseModel): """ @@ -37,68 +38,27 @@ class UnnamedDictWithAdditionalModelListProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in dict_property (dict of array) - _field_dict_of_array = {} - if self.dict_property: - for _key_dict_property in self.dict_property: - if self.dict_property[_key_dict_property] is not None: - _field_dict_of_array[_key_dict_property] = [ - _item.to_dict() for _item in self.dict_property[_key_dict_property] - ] - _dict['dictProperty'] = _field_dict_of_array - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalModelListProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "dictProperty": dict( - (_k, - [CreatureInfo.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("dictProperty", {}).items() - ) - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py index 477dcae27c7c..57629cf53b18 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UnnamedDictWithAdditionalStringListProperties(BaseModel): """ @@ -36,52 +37,27 @@ class UnnamedDictWithAdditionalStringListProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalStringListProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "dictProperty": obj.get("dictProperty") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/upload_file_with_additional_properties_request_object.py index 9040618ac0d7..2cfefd30dad8 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/upload_file_with_additional_properties_request_object.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): """ @@ -36,52 +37,27 @@ class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/user.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/user.py index 45e0a66f89dd..499f7f22d7a3 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/user.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/user.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class User(BaseModel): """ @@ -43,59 +44,27 @@ class User(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) - @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of User from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) - def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) + def to_dict(self) -> Dict[str, Any]: + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - return _dict + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of User from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "username": obj.get("username"), - "firstName": obj.get("firstName"), - "lastName": obj.get("lastName"), - "email": obj.get("email"), - "password": obj.get("password"), - "phone": obj.get("phone"), - "userStatus": obj.get("userStatus") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/with_nested_one_of.py b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/with_nested_one_of.py index f2cd8b7a3a30..2358231b1f89 100644 --- a/samples/openapi3/client/petstore/python-httpx/petstore_api/models/with_nested_one_of.py +++ b/samples/openapi3/client/petstore/python-httpx/petstore_api/models/with_nested_one_of.py @@ -22,7 +22,8 @@ from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.pig import Pig from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class WithNestedOneOf(BaseModel): """ @@ -40,57 +41,27 @@ class WithNestedOneOf(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of WithNestedOneOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - """ - excluded_fields: Set[str] = set([ - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested_pig - if self.nested_pig: - _dict['nested_pig'] = self.nested_pig.to_dict() - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of WithNestedOneOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested_pig": Pig.from_dict(obj["nested_pig"]) if obj.get("nested_pig") is not None else None, - "nested_oneof_enum_string": obj.get("nested_oneof_enum_string") - }) - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesAnyType.md b/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesAnyType.md index 314cba3a614c..b94c1e6d7d19 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesAnyType.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesAnyType.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_any_type import AdditionalPropert # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesAnyType from a JSON string -additional_properties_any_type_instance = AdditionalPropertiesAnyType.from_json(json) +additional_properties_any_type_instance = AdditionalPropertiesAnyType.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesAnyType.to_json()) +print(additional_properties_any_type_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_any_type_dict = additional_properties_any_type_instance.to_dict() +additional_properties_any_type_dict = additional_properties_any_type_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesAnyType from a dict -additional_properties_any_type_from_dict = AdditionalPropertiesAnyType.from_dict(additional_properties_any_type_dict) +additional_properties_any_type_from_dict = AdditionalPropertiesAnyType.model_validate(additional_properties_any_type_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesClass.md index 8d4c08707f55..4c880d6853e8 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesClass.md @@ -16,14 +16,14 @@ from petstore_api.models.additional_properties_class import AdditionalProperties # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesClass from a JSON string -additional_properties_class_instance = AdditionalPropertiesClass.from_json(json) +additional_properties_class_instance = AdditionalPropertiesClass.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesClass.to_json()) +print(additional_properties_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_class_dict = additional_properties_class_instance.to_dict() +additional_properties_class_dict = additional_properties_class_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesClass from a dict -additional_properties_class_from_dict = AdditionalPropertiesClass.from_dict(additional_properties_class_dict) +additional_properties_class_from_dict = AdditionalPropertiesClass.model_validate(additional_properties_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesObject.md b/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesObject.md index d647ec64896f..bf6743709338 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesObject.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesObject.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_object import AdditionalPropertie # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesObject from a JSON string -additional_properties_object_instance = AdditionalPropertiesObject.from_json(json) +additional_properties_object_instance = AdditionalPropertiesObject.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesObject.to_json()) +print(additional_properties_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_object_dict = additional_properties_object_instance.to_dict() +additional_properties_object_dict = additional_properties_object_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesObject from a dict -additional_properties_object_from_dict = AdditionalPropertiesObject.from_dict(additional_properties_object_dict) +additional_properties_object_from_dict = AdditionalPropertiesObject.model_validate(additional_properties_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesWithDescriptionOnly.md b/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesWithDescriptionOnly.md index 061f5524872b..1cb2a02f7584 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesWithDescriptionOnly.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/AdditionalPropertiesWithDescriptionOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_with_description_only import Addi # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string -additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.from_json(json) +additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesWithDescriptionOnly.to_json()) +print(additional_properties_with_description_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.to_dict() +additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesWithDescriptionOnly from a dict -additional_properties_with_description_only_from_dict = AdditionalPropertiesWithDescriptionOnly.from_dict(additional_properties_with_description_only_dict) +additional_properties_with_description_only_from_dict = AdditionalPropertiesWithDescriptionOnly.model_validate(additional_properties_with_description_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/AllOfSuperModel.md b/samples/openapi3/client/petstore/python-lazyImports/docs/AllOfSuperModel.md index 421a1527f1ef..88cb95097517 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/AllOfSuperModel.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/AllOfSuperModel.md @@ -15,14 +15,14 @@ from petstore_api.models.all_of_super_model import AllOfSuperModel # TODO update the JSON string below json = "{}" # create an instance of AllOfSuperModel from a JSON string -all_of_super_model_instance = AllOfSuperModel.from_json(json) +all_of_super_model_instance = AllOfSuperModel.model_validate_json(json) # print the JSON string representation of the object -print(AllOfSuperModel.to_json()) +print(all_of_super_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -all_of_super_model_dict = all_of_super_model_instance.to_dict() +all_of_super_model_dict = all_of_super_model_instance.model_dump(by_alias=True) # create an instance of AllOfSuperModel from a dict -all_of_super_model_from_dict = AllOfSuperModel.from_dict(all_of_super_model_dict) +all_of_super_model_from_dict = AllOfSuperModel.model_validate(all_of_super_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/AllOfWithSingleRef.md b/samples/openapi3/client/petstore/python-lazyImports/docs/AllOfWithSingleRef.md index 203a4b5da3d5..dd0f755dfe65 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/AllOfWithSingleRef.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/AllOfWithSingleRef.md @@ -16,14 +16,14 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef # TODO update the JSON string below json = "{}" # create an instance of AllOfWithSingleRef from a JSON string -all_of_with_single_ref_instance = AllOfWithSingleRef.from_json(json) +all_of_with_single_ref_instance = AllOfWithSingleRef.model_validate_json(json) # print the JSON string representation of the object -print(AllOfWithSingleRef.to_json()) +print(all_of_with_single_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -all_of_with_single_ref_dict = all_of_with_single_ref_instance.to_dict() +all_of_with_single_ref_dict = all_of_with_single_ref_instance.model_dump(by_alias=True) # create an instance of AllOfWithSingleRef from a dict -all_of_with_single_ref_from_dict = AllOfWithSingleRef.from_dict(all_of_with_single_ref_dict) +all_of_with_single_ref_from_dict = AllOfWithSingleRef.model_validate(all_of_with_single_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Animal.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Animal.md index 381d27b66e44..fcded75f52be 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Animal.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Animal.md @@ -16,14 +16,14 @@ from petstore_api.models.animal import Animal # TODO update the JSON string below json = "{}" # create an instance of Animal from a JSON string -animal_instance = Animal.from_json(json) +animal_instance = Animal.model_validate_json(json) # print the JSON string representation of the object -print(Animal.to_json()) +print(animal_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -animal_dict = animal_instance.to_dict() +animal_dict = animal_instance.model_dump(by_alias=True) # create an instance of Animal from a dict -animal_from_dict = Animal.from_dict(animal_dict) +animal_from_dict = Animal.model_validate(animal_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfColor.md b/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfColor.md index 6ed75dd7b48a..02aab883b2b0 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfColor.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfColor.md @@ -15,14 +15,14 @@ from petstore_api.models.any_of_color import AnyOfColor # TODO update the JSON string below json = "{}" # create an instance of AnyOfColor from a JSON string -any_of_color_instance = AnyOfColor.from_json(json) +any_of_color_instance = AnyOfColor.model_validate_json(json) # print the JSON string representation of the object -print(AnyOfColor.to_json()) +print(any_of_color_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -any_of_color_dict = any_of_color_instance.to_dict() +any_of_color_dict = any_of_color_instance.model_dump(by_alias=True) # create an instance of AnyOfColor from a dict -any_of_color_from_dict = AnyOfColor.from_dict(any_of_color_dict) +any_of_color_from_dict = AnyOfColor.model_validate(any_of_color_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfPig.md b/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfPig.md index 9367e2261898..db2878121f29 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfPig.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/AnyOfPig.md @@ -17,14 +17,14 @@ from petstore_api.models.any_of_pig import AnyOfPig # TODO update the JSON string below json = "{}" # create an instance of AnyOfPig from a JSON string -any_of_pig_instance = AnyOfPig.from_json(json) +any_of_pig_instance = AnyOfPig.model_validate_json(json) # print the JSON string representation of the object -print(AnyOfPig.to_json()) +print(any_of_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -any_of_pig_dict = any_of_pig_instance.to_dict() +any_of_pig_dict = any_of_pig_instance.model_dump(by_alias=True) # create an instance of AnyOfPig from a dict -any_of_pig_from_dict = AnyOfPig.from_dict(any_of_pig_dict) +any_of_pig_from_dict = AnyOfPig.model_validate(any_of_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfArrayOfModel.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfArrayOfModel.md index f866863d53f9..e8274d8fbb52 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfArrayOfModel.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel # TODO update the JSON string below json = "{}" # create an instance of ArrayOfArrayOfModel from a JSON string -array_of_array_of_model_instance = ArrayOfArrayOfModel.from_json(json) +array_of_array_of_model_instance = ArrayOfArrayOfModel.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfArrayOfModel.to_json()) +print(array_of_array_of_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_array_of_model_dict = array_of_array_of_model_instance.to_dict() +array_of_array_of_model_dict = array_of_array_of_model_instance.model_dump(by_alias=True) # create an instance of ArrayOfArrayOfModel from a dict -array_of_array_of_model_from_dict = ArrayOfArrayOfModel.from_dict(array_of_array_of_model_dict) +array_of_array_of_model_from_dict = ArrayOfArrayOfModel.model_validate(array_of_array_of_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfArrayOfNumberOnly.md index 32bd2dfbf1e2..8931a1c7e467 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfArrayOfNumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumb # TODO update the JSON string below json = "{}" # create an instance of ArrayOfArrayOfNumberOnly from a JSON string -array_of_array_of_number_only_instance = ArrayOfArrayOfNumberOnly.from_json(json) +array_of_array_of_number_only_instance = ArrayOfArrayOfNumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfArrayOfNumberOnly.to_json()) +print(array_of_array_of_number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_array_of_number_only_dict = array_of_array_of_number_only_instance.to_dict() +array_of_array_of_number_only_dict = array_of_array_of_number_only_instance.model_dump(by_alias=True) # create an instance of ArrayOfArrayOfNumberOnly from a dict -array_of_array_of_number_only_from_dict = ArrayOfArrayOfNumberOnly.from_dict(array_of_array_of_number_only_dict) +array_of_array_of_number_only_from_dict = ArrayOfArrayOfNumberOnly.model_validate(array_of_array_of_number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfNumberOnly.md index b814d7594942..a709583be699 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayOfNumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly # TODO update the JSON string below json = "{}" # create an instance of ArrayOfNumberOnly from a JSON string -array_of_number_only_instance = ArrayOfNumberOnly.from_json(json) +array_of_number_only_instance = ArrayOfNumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfNumberOnly.to_json()) +print(array_of_number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_number_only_dict = array_of_number_only_instance.to_dict() +array_of_number_only_dict = array_of_number_only_instance.model_dump(by_alias=True) # create an instance of ArrayOfNumberOnly from a dict -array_of_number_only_from_dict = ArrayOfNumberOnly.from_dict(array_of_number_only_dict) +array_of_number_only_from_dict = ArrayOfNumberOnly.model_validate(array_of_number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayTest.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayTest.md index ed871fae662d..a99eb056c5ca 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayTest.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ArrayTest.md @@ -18,14 +18,14 @@ from petstore_api.models.array_test import ArrayTest # TODO update the JSON string below json = "{}" # create an instance of ArrayTest from a JSON string -array_test_instance = ArrayTest.from_json(json) +array_test_instance = ArrayTest.model_validate_json(json) # print the JSON string representation of the object -print(ArrayTest.to_json()) +print(array_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_test_dict = array_test_instance.to_dict() +array_test_dict = array_test_instance.model_dump(by_alias=True) # create an instance of ArrayTest from a dict -array_test_from_dict = ArrayTest.from_dict(array_test_dict) +array_test_from_dict = ArrayTest.model_validate(array_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/BaseDiscriminator.md b/samples/openapi3/client/petstore/python-lazyImports/docs/BaseDiscriminator.md index fcdbeb032e68..0482396cbcf8 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/BaseDiscriminator.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/BaseDiscriminator.md @@ -15,14 +15,14 @@ from petstore_api.models.base_discriminator import BaseDiscriminator # TODO update the JSON string below json = "{}" # create an instance of BaseDiscriminator from a JSON string -base_discriminator_instance = BaseDiscriminator.from_json(json) +base_discriminator_instance = BaseDiscriminator.model_validate_json(json) # print the JSON string representation of the object -print(BaseDiscriminator.to_json()) +print(base_discriminator_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -base_discriminator_dict = base_discriminator_instance.to_dict() +base_discriminator_dict = base_discriminator_instance.model_dump(by_alias=True) # create an instance of BaseDiscriminator from a dict -base_discriminator_from_dict = BaseDiscriminator.from_dict(base_discriminator_dict) +base_discriminator_from_dict = BaseDiscriminator.model_validate(base_discriminator_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/BasquePig.md b/samples/openapi3/client/petstore/python-lazyImports/docs/BasquePig.md index ee28d628722f..9844d05b3740 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/BasquePig.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/BasquePig.md @@ -16,14 +16,14 @@ from petstore_api.models.basque_pig import BasquePig # TODO update the JSON string below json = "{}" # create an instance of BasquePig from a JSON string -basque_pig_instance = BasquePig.from_json(json) +basque_pig_instance = BasquePig.model_validate_json(json) # print the JSON string representation of the object -print(BasquePig.to_json()) +print(basque_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -basque_pig_dict = basque_pig_instance.to_dict() +basque_pig_dict = basque_pig_instance.model_dump(by_alias=True) # create an instance of BasquePig from a dict -basque_pig_from_dict = BasquePig.from_dict(basque_pig_dict) +basque_pig_from_dict = BasquePig.model_validate(basque_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Bathing.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Bathing.md index 6ad70e2f67cc..2c8d8332629b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Bathing.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Bathing.md @@ -17,14 +17,14 @@ from petstore_api.models.bathing import Bathing # TODO update the JSON string below json = "{}" # create an instance of Bathing from a JSON string -bathing_instance = Bathing.from_json(json) +bathing_instance = Bathing.model_validate_json(json) # print the JSON string representation of the object -print(Bathing.to_json()) +print(bathing_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -bathing_dict = bathing_instance.to_dict() +bathing_dict = bathing_instance.model_dump(by_alias=True) # create an instance of Bathing from a dict -bathing_from_dict = Bathing.from_dict(bathing_dict) +bathing_from_dict = Bathing.model_validate(bathing_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Capitalization.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Capitalization.md index 6f564a8ed8c9..55fcc0c01cb2 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Capitalization.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Capitalization.md @@ -20,14 +20,14 @@ from petstore_api.models.capitalization import Capitalization # TODO update the JSON string below json = "{}" # create an instance of Capitalization from a JSON string -capitalization_instance = Capitalization.from_json(json) +capitalization_instance = Capitalization.model_validate_json(json) # print the JSON string representation of the object -print(Capitalization.to_json()) +print(capitalization_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -capitalization_dict = capitalization_instance.to_dict() +capitalization_dict = capitalization_instance.model_dump(by_alias=True) # create an instance of Capitalization from a dict -capitalization_from_dict = Capitalization.from_dict(capitalization_dict) +capitalization_from_dict = Capitalization.model_validate(capitalization_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Cat.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Cat.md index d0e39efdb33e..0845d68bd487 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Cat.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Cat.md @@ -15,14 +15,14 @@ from petstore_api.models.cat import Cat # TODO update the JSON string below json = "{}" # create an instance of Cat from a JSON string -cat_instance = Cat.from_json(json) +cat_instance = Cat.model_validate_json(json) # print the JSON string representation of the object -print(Cat.to_json()) +print(cat_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -cat_dict = cat_instance.to_dict() +cat_dict = cat_instance.model_dump(by_alias=True) # create an instance of Cat from a dict -cat_from_dict = Cat.from_dict(cat_dict) +cat_from_dict = Cat.model_validate(cat_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Category.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Category.md index dbde14b7344c..8a14791c7925 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Category.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Category.md @@ -16,14 +16,14 @@ from petstore_api.models.category import Category # TODO update the JSON string below json = "{}" # create an instance of Category from a JSON string -category_instance = Category.from_json(json) +category_instance = Category.model_validate_json(json) # print the JSON string representation of the object -print(Category.to_json()) +print(category_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -category_dict = category_instance.to_dict() +category_dict = category_instance.model_dump(by_alias=True) # create an instance of Category from a dict -category_from_dict = Category.from_dict(category_dict) +category_from_dict = Category.model_validate(category_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/CircularAllOfRef.md b/samples/openapi3/client/petstore/python-lazyImports/docs/CircularAllOfRef.md index 65b171177e58..f937a53cfe3c 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/CircularAllOfRef.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/CircularAllOfRef.md @@ -16,14 +16,14 @@ from petstore_api.models.circular_all_of_ref import CircularAllOfRef # TODO update the JSON string below json = "{}" # create an instance of CircularAllOfRef from a JSON string -circular_all_of_ref_instance = CircularAllOfRef.from_json(json) +circular_all_of_ref_instance = CircularAllOfRef.model_validate_json(json) # print the JSON string representation of the object -print(CircularAllOfRef.to_json()) +print(circular_all_of_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -circular_all_of_ref_dict = circular_all_of_ref_instance.to_dict() +circular_all_of_ref_dict = circular_all_of_ref_instance.model_dump(by_alias=True) # create an instance of CircularAllOfRef from a dict -circular_all_of_ref_from_dict = CircularAllOfRef.from_dict(circular_all_of_ref_dict) +circular_all_of_ref_from_dict = CircularAllOfRef.model_validate(circular_all_of_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/CircularReferenceModel.md b/samples/openapi3/client/petstore/python-lazyImports/docs/CircularReferenceModel.md index 87216f7273ab..9a39f46e5d7d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/CircularReferenceModel.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/CircularReferenceModel.md @@ -16,14 +16,14 @@ from petstore_api.models.circular_reference_model import CircularReferenceModel # TODO update the JSON string below json = "{}" # create an instance of CircularReferenceModel from a JSON string -circular_reference_model_instance = CircularReferenceModel.from_json(json) +circular_reference_model_instance = CircularReferenceModel.model_validate_json(json) # print the JSON string representation of the object -print(CircularReferenceModel.to_json()) +print(circular_reference_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -circular_reference_model_dict = circular_reference_model_instance.to_dict() +circular_reference_model_dict = circular_reference_model_instance.model_dump(by_alias=True) # create an instance of CircularReferenceModel from a dict -circular_reference_model_from_dict = CircularReferenceModel.from_dict(circular_reference_model_dict) +circular_reference_model_from_dict = CircularReferenceModel.model_validate(circular_reference_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ClassModel.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ClassModel.md index ea76a5c157bf..50fbfefa7661 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ClassModel.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ClassModel.md @@ -16,14 +16,14 @@ from petstore_api.models.class_model import ClassModel # TODO update the JSON string below json = "{}" # create an instance of ClassModel from a JSON string -class_model_instance = ClassModel.from_json(json) +class_model_instance = ClassModel.model_validate_json(json) # print the JSON string representation of the object -print(ClassModel.to_json()) +print(class_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -class_model_dict = class_model_instance.to_dict() +class_model_dict = class_model_instance.model_dump(by_alias=True) # create an instance of ClassModel from a dict -class_model_from_dict = ClassModel.from_dict(class_model_dict) +class_model_from_dict = ClassModel.model_validate(class_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Client.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Client.md index 22321c189150..160a80da457f 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Client.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Client.md @@ -15,14 +15,14 @@ from petstore_api.models.client import Client # TODO update the JSON string below json = "{}" # create an instance of Client from a JSON string -client_instance = Client.from_json(json) +client_instance = Client.model_validate_json(json) # print the JSON string representation of the object -print(Client.to_json()) +print(client_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -client_dict = client_instance.to_dict() +client_dict = client_instance.model_dump(by_alias=True) # create an instance of Client from a dict -client_from_dict = Client.from_dict(client_dict) +client_from_dict = Client.model_validate(client_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Color.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Color.md index 9ac3ab2e91f4..1425ff185040 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Color.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Color.md @@ -15,14 +15,14 @@ from petstore_api.models.color import Color # TODO update the JSON string below json = "{}" # create an instance of Color from a JSON string -color_instance = Color.from_json(json) +color_instance = Color.model_validate_json(json) # print the JSON string representation of the object -print(Color.to_json()) +print(color_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -color_dict = color_instance.to_dict() +color_dict = color_instance.model_dump(by_alias=True) # create an instance of Color from a dict -color_from_dict = Color.from_dict(color_dict) +color_from_dict = Color.model_validate(color_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Creature.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Creature.md index a4710214c198..eb0ba3b2f127 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Creature.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Creature.md @@ -16,14 +16,14 @@ from petstore_api.models.creature import Creature # TODO update the JSON string below json = "{}" # create an instance of Creature from a JSON string -creature_instance = Creature.from_json(json) +creature_instance = Creature.model_validate_json(json) # print the JSON string representation of the object -print(Creature.to_json()) +print(creature_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -creature_dict = creature_instance.to_dict() +creature_dict = creature_instance.model_dump(by_alias=True) # create an instance of Creature from a dict -creature_from_dict = Creature.from_dict(creature_dict) +creature_from_dict = Creature.model_validate(creature_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/CreatureInfo.md b/samples/openapi3/client/petstore/python-lazyImports/docs/CreatureInfo.md index db3b82bb9ff5..156d93939201 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/CreatureInfo.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/CreatureInfo.md @@ -15,14 +15,14 @@ from petstore_api.models.creature_info import CreatureInfo # TODO update the JSON string below json = "{}" # create an instance of CreatureInfo from a JSON string -creature_info_instance = CreatureInfo.from_json(json) +creature_info_instance = CreatureInfo.model_validate_json(json) # print the JSON string representation of the object -print(CreatureInfo.to_json()) +print(creature_info_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -creature_info_dict = creature_info_instance.to_dict() +creature_info_dict = creature_info_instance.model_dump(by_alias=True) # create an instance of CreatureInfo from a dict -creature_info_from_dict = CreatureInfo.from_dict(creature_info_dict) +creature_info_from_dict = CreatureInfo.model_validate(creature_info_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/DanishPig.md b/samples/openapi3/client/petstore/python-lazyImports/docs/DanishPig.md index 16941388832a..5eac27f79e79 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/DanishPig.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/DanishPig.md @@ -16,14 +16,14 @@ from petstore_api.models.danish_pig import DanishPig # TODO update the JSON string below json = "{}" # create an instance of DanishPig from a JSON string -danish_pig_instance = DanishPig.from_json(json) +danish_pig_instance = DanishPig.model_validate_json(json) # print the JSON string representation of the object -print(DanishPig.to_json()) +print(danish_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -danish_pig_dict = danish_pig_instance.to_dict() +danish_pig_dict = danish_pig_instance.model_dump(by_alias=True) # create an instance of DanishPig from a dict -danish_pig_from_dict = DanishPig.from_dict(danish_pig_dict) +danish_pig_from_dict = DanishPig.model_validate(danish_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/DeprecatedObject.md b/samples/openapi3/client/petstore/python-lazyImports/docs/DeprecatedObject.md index 6b362f379ba4..ff3aa9812e2d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/DeprecatedObject.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/DeprecatedObject.md @@ -15,14 +15,14 @@ from petstore_api.models.deprecated_object import DeprecatedObject # TODO update the JSON string below json = "{}" # create an instance of DeprecatedObject from a JSON string -deprecated_object_instance = DeprecatedObject.from_json(json) +deprecated_object_instance = DeprecatedObject.model_validate_json(json) # print the JSON string representation of the object -print(DeprecatedObject.to_json()) +print(deprecated_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -deprecated_object_dict = deprecated_object_instance.to_dict() +deprecated_object_dict = deprecated_object_instance.model_dump(by_alias=True) # create an instance of DeprecatedObject from a dict -deprecated_object_from_dict = DeprecatedObject.from_dict(deprecated_object_dict) +deprecated_object_from_dict = DeprecatedObject.model_validate(deprecated_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/DiscriminatorAllOfSub.md b/samples/openapi3/client/petstore/python-lazyImports/docs/DiscriminatorAllOfSub.md index f72b6e8e68ca..aa7af45b99fa 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/DiscriminatorAllOfSub.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/DiscriminatorAllOfSub.md @@ -14,14 +14,14 @@ from petstore_api.models.discriminator_all_of_sub import DiscriminatorAllOfSub # TODO update the JSON string below json = "{}" # create an instance of DiscriminatorAllOfSub from a JSON string -discriminator_all_of_sub_instance = DiscriminatorAllOfSub.from_json(json) +discriminator_all_of_sub_instance = DiscriminatorAllOfSub.model_validate_json(json) # print the JSON string representation of the object -print(DiscriminatorAllOfSub.to_json()) +print(discriminator_all_of_sub_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -discriminator_all_of_sub_dict = discriminator_all_of_sub_instance.to_dict() +discriminator_all_of_sub_dict = discriminator_all_of_sub_instance.model_dump(by_alias=True) # create an instance of DiscriminatorAllOfSub from a dict -discriminator_all_of_sub_from_dict = DiscriminatorAllOfSub.from_dict(discriminator_all_of_sub_dict) +discriminator_all_of_sub_from_dict = DiscriminatorAllOfSub.model_validate(discriminator_all_of_sub_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/DiscriminatorAllOfSuper.md b/samples/openapi3/client/petstore/python-lazyImports/docs/DiscriminatorAllOfSuper.md index 477c05bfc446..c21e5b2296ac 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/DiscriminatorAllOfSuper.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/DiscriminatorAllOfSuper.md @@ -15,14 +15,14 @@ from petstore_api.models.discriminator_all_of_super import DiscriminatorAllOfSup # TODO update the JSON string below json = "{}" # create an instance of DiscriminatorAllOfSuper from a JSON string -discriminator_all_of_super_instance = DiscriminatorAllOfSuper.from_json(json) +discriminator_all_of_super_instance = DiscriminatorAllOfSuper.model_validate_json(json) # print the JSON string representation of the object -print(DiscriminatorAllOfSuper.to_json()) +print(discriminator_all_of_super_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -discriminator_all_of_super_dict = discriminator_all_of_super_instance.to_dict() +discriminator_all_of_super_dict = discriminator_all_of_super_instance.model_dump(by_alias=True) # create an instance of DiscriminatorAllOfSuper from a dict -discriminator_all_of_super_from_dict = DiscriminatorAllOfSuper.from_dict(discriminator_all_of_super_dict) +discriminator_all_of_super_from_dict = DiscriminatorAllOfSuper.model_validate(discriminator_all_of_super_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Dog.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Dog.md index ed23f613d01d..2065d42f5f6b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Dog.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Dog.md @@ -15,14 +15,14 @@ from petstore_api.models.dog import Dog # TODO update the JSON string below json = "{}" # create an instance of Dog from a JSON string -dog_instance = Dog.from_json(json) +dog_instance = Dog.model_validate_json(json) # print the JSON string representation of the object -print(Dog.to_json()) +print(dog_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -dog_dict = dog_instance.to_dict() +dog_dict = dog_instance.model_dump(by_alias=True) # create an instance of Dog from a dict -dog_from_dict = Dog.from_dict(dog_dict) +dog_from_dict = Dog.model_validate(dog_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/DummyModel.md b/samples/openapi3/client/petstore/python-lazyImports/docs/DummyModel.md index 01b675977f58..dfe28d9f75b1 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/DummyModel.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/DummyModel.md @@ -16,14 +16,14 @@ from petstore_api.models.dummy_model import DummyModel # TODO update the JSON string below json = "{}" # create an instance of DummyModel from a JSON string -dummy_model_instance = DummyModel.from_json(json) +dummy_model_instance = DummyModel.model_validate_json(json) # print the JSON string representation of the object -print(DummyModel.to_json()) +print(dummy_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -dummy_model_dict = dummy_model_instance.to_dict() +dummy_model_dict = dummy_model_instance.model_dump(by_alias=True) # create an instance of DummyModel from a dict -dummy_model_from_dict = DummyModel.from_dict(dummy_model_dict) +dummy_model_from_dict = DummyModel.model_validate(dummy_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/EnumArrays.md b/samples/openapi3/client/petstore/python-lazyImports/docs/EnumArrays.md index f44617497bce..bf8b1a6cd05c 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/EnumArrays.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/EnumArrays.md @@ -16,14 +16,14 @@ from petstore_api.models.enum_arrays import EnumArrays # TODO update the JSON string below json = "{}" # create an instance of EnumArrays from a JSON string -enum_arrays_instance = EnumArrays.from_json(json) +enum_arrays_instance = EnumArrays.model_validate_json(json) # print the JSON string representation of the object -print(EnumArrays.to_json()) +print(enum_arrays_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_arrays_dict = enum_arrays_instance.to_dict() +enum_arrays_dict = enum_arrays_instance.model_dump(by_alias=True) # create an instance of EnumArrays from a dict -enum_arrays_from_dict = EnumArrays.from_dict(enum_arrays_dict) +enum_arrays_from_dict = EnumArrays.model_validate(enum_arrays_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/EnumRefWithDefaultValue.md b/samples/openapi3/client/petstore/python-lazyImports/docs/EnumRefWithDefaultValue.md index eeb0dc66969f..cbe6845479eb 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/EnumRefWithDefaultValue.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/EnumRefWithDefaultValue.md @@ -15,14 +15,14 @@ from petstore_api.models.enum_ref_with_default_value import EnumRefWithDefaultVa # TODO update the JSON string below json = "{}" # create an instance of EnumRefWithDefaultValue from a JSON string -enum_ref_with_default_value_instance = EnumRefWithDefaultValue.from_json(json) +enum_ref_with_default_value_instance = EnumRefWithDefaultValue.model_validate_json(json) # print the JSON string representation of the object -print(EnumRefWithDefaultValue.to_json()) +print(enum_ref_with_default_value_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_ref_with_default_value_dict = enum_ref_with_default_value_instance.to_dict() +enum_ref_with_default_value_dict = enum_ref_with_default_value_instance.model_dump(by_alias=True) # create an instance of EnumRefWithDefaultValue from a dict -enum_ref_with_default_value_from_dict = EnumRefWithDefaultValue.from_dict(enum_ref_with_default_value_dict) +enum_ref_with_default_value_from_dict = EnumRefWithDefaultValue.model_validate(enum_ref_with_default_value_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/EnumTest.md b/samples/openapi3/client/petstore/python-lazyImports/docs/EnumTest.md index 9f96c605d888..6ce4891aa9d5 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/EnumTest.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/EnumTest.md @@ -27,14 +27,14 @@ from petstore_api.models.enum_test import EnumTest # TODO update the JSON string below json = "{}" # create an instance of EnumTest from a JSON string -enum_test_instance = EnumTest.from_json(json) +enum_test_instance = EnumTest.model_validate_json(json) # print the JSON string representation of the object -print(EnumTest.to_json()) +print(enum_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_test_dict = enum_test_instance.to_dict() +enum_test_dict = enum_test_instance.model_dump(by_alias=True) # create an instance of EnumTest from a dict -enum_test_from_dict = EnumTest.from_dict(enum_test_dict) +enum_test_from_dict = EnumTest.model_validate(enum_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Feeding.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Feeding.md index 9f92b5d964d3..773d1373cca0 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Feeding.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Feeding.md @@ -17,14 +17,14 @@ from petstore_api.models.feeding import Feeding # TODO update the JSON string below json = "{}" # create an instance of Feeding from a JSON string -feeding_instance = Feeding.from_json(json) +feeding_instance = Feeding.model_validate_json(json) # print the JSON string representation of the object -print(Feeding.to_json()) +print(feeding_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -feeding_dict = feeding_instance.to_dict() +feeding_dict = feeding_instance.model_dump(by_alias=True) # create an instance of Feeding from a dict -feeding_from_dict = Feeding.from_dict(feeding_dict) +feeding_from_dict = Feeding.model_validate(feeding_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/File.md b/samples/openapi3/client/petstore/python-lazyImports/docs/File.md index 23f0567411ce..3fe748f4f30f 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/File.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/File.md @@ -16,14 +16,14 @@ from petstore_api.models.file import File # TODO update the JSON string below json = "{}" # create an instance of File from a JSON string -file_instance = File.from_json(json) +file_instance = File.model_validate_json(json) # print the JSON string representation of the object -print(File.to_json()) +print(file_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -file_dict = file_instance.to_dict() +file_dict = file_instance.model_dump(by_alias=True) # create an instance of File from a dict -file_from_dict = File.from_dict(file_dict) +file_from_dict = File.model_validate(file_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python-lazyImports/docs/FileSchemaTestClass.md index e1118042a8ec..78bc4ae135da 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/FileSchemaTestClass.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/FileSchemaTestClass.md @@ -16,14 +16,14 @@ from petstore_api.models.file_schema_test_class import FileSchemaTestClass # TODO update the JSON string below json = "{}" # create an instance of FileSchemaTestClass from a JSON string -file_schema_test_class_instance = FileSchemaTestClass.from_json(json) +file_schema_test_class_instance = FileSchemaTestClass.model_validate_json(json) # print the JSON string representation of the object -print(FileSchemaTestClass.to_json()) +print(file_schema_test_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -file_schema_test_class_dict = file_schema_test_class_instance.to_dict() +file_schema_test_class_dict = file_schema_test_class_instance.model_dump(by_alias=True) # create an instance of FileSchemaTestClass from a dict -file_schema_test_class_from_dict = FileSchemaTestClass.from_dict(file_schema_test_class_dict) +file_schema_test_class_from_dict = FileSchemaTestClass.model_validate(file_schema_test_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/FirstRef.md b/samples/openapi3/client/petstore/python-lazyImports/docs/FirstRef.md index 94b8ddc5ac22..6da6650e5df7 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/FirstRef.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/FirstRef.md @@ -16,14 +16,14 @@ from petstore_api.models.first_ref import FirstRef # TODO update the JSON string below json = "{}" # create an instance of FirstRef from a JSON string -first_ref_instance = FirstRef.from_json(json) +first_ref_instance = FirstRef.model_validate_json(json) # print the JSON string representation of the object -print(FirstRef.to_json()) +print(first_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -first_ref_dict = first_ref_instance.to_dict() +first_ref_dict = first_ref_instance.model_dump(by_alias=True) # create an instance of FirstRef from a dict -first_ref_from_dict = FirstRef.from_dict(first_ref_dict) +first_ref_from_dict = FirstRef.model_validate(first_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Foo.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Foo.md index f635b0daa6db..c11ae111ee22 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Foo.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Foo.md @@ -15,14 +15,14 @@ from petstore_api.models.foo import Foo # TODO update the JSON string below json = "{}" # create an instance of Foo from a JSON string -foo_instance = Foo.from_json(json) +foo_instance = Foo.model_validate_json(json) # print the JSON string representation of the object -print(Foo.to_json()) +print(foo_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -foo_dict = foo_instance.to_dict() +foo_dict = foo_instance.model_dump(by_alias=True) # create an instance of Foo from a dict -foo_from_dict = Foo.from_dict(foo_dict) +foo_from_dict = Foo.model_validate(foo_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/FooGetDefaultResponse.md b/samples/openapi3/client/petstore/python-lazyImports/docs/FooGetDefaultResponse.md index 8d84f795b00a..aaccf08bfd2e 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/FooGetDefaultResponse.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/FooGetDefaultResponse.md @@ -15,14 +15,14 @@ from petstore_api.models.foo_get_default_response import FooGetDefaultResponse # TODO update the JSON string below json = "{}" # create an instance of FooGetDefaultResponse from a JSON string -foo_get_default_response_instance = FooGetDefaultResponse.from_json(json) +foo_get_default_response_instance = FooGetDefaultResponse.model_validate_json(json) # print the JSON string representation of the object -print(FooGetDefaultResponse.to_json()) +print(foo_get_default_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -foo_get_default_response_dict = foo_get_default_response_instance.to_dict() +foo_get_default_response_dict = foo_get_default_response_instance.model_dump(by_alias=True) # create an instance of FooGetDefaultResponse from a dict -foo_get_default_response_from_dict = FooGetDefaultResponse.from_dict(foo_get_default_response_dict) +foo_get_default_response_from_dict = FooGetDefaultResponse.model_validate(foo_get_default_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/FormatTest.md b/samples/openapi3/client/petstore/python-lazyImports/docs/FormatTest.md index 714d2401bbae..98c3dc89570d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/FormatTest.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/FormatTest.md @@ -31,14 +31,14 @@ from petstore_api.models.format_test import FormatTest # TODO update the JSON string below json = "{}" # create an instance of FormatTest from a JSON string -format_test_instance = FormatTest.from_json(json) +format_test_instance = FormatTest.model_validate_json(json) # print the JSON string representation of the object -print(FormatTest.to_json()) +print(format_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -format_test_dict = format_test_instance.to_dict() +format_test_dict = format_test_instance.model_dump(by_alias=True) # create an instance of FormatTest from a dict -format_test_from_dict = FormatTest.from_dict(format_test_dict) +format_test_from_dict = FormatTest.model_validate(format_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python-lazyImports/docs/HasOnlyReadOnly.md index fdc48781b15a..66dca11251aa 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/HasOnlyReadOnly.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/HasOnlyReadOnly.md @@ -16,14 +16,14 @@ from petstore_api.models.has_only_read_only import HasOnlyReadOnly # TODO update the JSON string below json = "{}" # create an instance of HasOnlyReadOnly from a JSON string -has_only_read_only_instance = HasOnlyReadOnly.from_json(json) +has_only_read_only_instance = HasOnlyReadOnly.model_validate_json(json) # print the JSON string representation of the object -print(HasOnlyReadOnly.to_json()) +print(has_only_read_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -has_only_read_only_dict = has_only_read_only_instance.to_dict() +has_only_read_only_dict = has_only_read_only_instance.model_dump(by_alias=True) # create an instance of HasOnlyReadOnly from a dict -has_only_read_only_from_dict = HasOnlyReadOnly.from_dict(has_only_read_only_dict) +has_only_read_only_from_dict = HasOnlyReadOnly.model_validate(has_only_read_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python-lazyImports/docs/HealthCheckResult.md index d4a2b187167f..522156ae5b16 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/HealthCheckResult.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/HealthCheckResult.md @@ -16,14 +16,14 @@ from petstore_api.models.health_check_result import HealthCheckResult # TODO update the JSON string below json = "{}" # create an instance of HealthCheckResult from a JSON string -health_check_result_instance = HealthCheckResult.from_json(json) +health_check_result_instance = HealthCheckResult.model_validate_json(json) # print the JSON string representation of the object -print(HealthCheckResult.to_json()) +print(health_check_result_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -health_check_result_dict = health_check_result_instance.to_dict() +health_check_result_dict = health_check_result_instance.model_dump(by_alias=True) # create an instance of HealthCheckResult from a dict -health_check_result_from_dict = HealthCheckResult.from_dict(health_check_result_dict) +health_check_result_from_dict = HealthCheckResult.model_validate(health_check_result_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/HuntingDog.md b/samples/openapi3/client/petstore/python-lazyImports/docs/HuntingDog.md index 6db6745dd022..114dfc8575d9 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/HuntingDog.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/HuntingDog.md @@ -15,14 +15,14 @@ from petstore_api.models.hunting_dog import HuntingDog # TODO update the JSON string below json = "{}" # create an instance of HuntingDog from a JSON string -hunting_dog_instance = HuntingDog.from_json(json) +hunting_dog_instance = HuntingDog.model_validate_json(json) # print the JSON string representation of the object -print(HuntingDog.to_json()) +print(hunting_dog_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -hunting_dog_dict = hunting_dog_instance.to_dict() +hunting_dog_dict = hunting_dog_instance.model_dump(by_alias=True) # create an instance of HuntingDog from a dict -hunting_dog_from_dict = HuntingDog.from_dict(hunting_dog_dict) +hunting_dog_from_dict = HuntingDog.model_validate(hunting_dog_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Info.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Info.md index db88778a9143..160c3633247c 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Info.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Info.md @@ -15,14 +15,14 @@ from petstore_api.models.info import Info # TODO update the JSON string below json = "{}" # create an instance of Info from a JSON string -info_instance = Info.from_json(json) +info_instance = Info.model_validate_json(json) # print the JSON string representation of the object -print(Info.to_json()) +print(info_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -info_dict = info_instance.to_dict() +info_dict = info_instance.model_dump(by_alias=True) # create an instance of Info from a dict -info_from_dict = Info.from_dict(info_dict) +info_from_dict = Info.model_validate(info_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/InnerDictWithProperty.md b/samples/openapi3/client/petstore/python-lazyImports/docs/InnerDictWithProperty.md index 7b82ebb770b8..79234d754027 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/InnerDictWithProperty.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/InnerDictWithProperty.md @@ -15,14 +15,14 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty # TODO update the JSON string below json = "{}" # create an instance of InnerDictWithProperty from a JSON string -inner_dict_with_property_instance = InnerDictWithProperty.from_json(json) +inner_dict_with_property_instance = InnerDictWithProperty.model_validate_json(json) # print the JSON string representation of the object -print(InnerDictWithProperty.to_json()) +print(inner_dict_with_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -inner_dict_with_property_dict = inner_dict_with_property_instance.to_dict() +inner_dict_with_property_dict = inner_dict_with_property_instance.model_dump(by_alias=True) # create an instance of InnerDictWithProperty from a dict -inner_dict_with_property_from_dict = InnerDictWithProperty.from_dict(inner_dict_with_property_dict) +inner_dict_with_property_from_dict = InnerDictWithProperty.model_validate(inner_dict_with_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/InputAllOf.md b/samples/openapi3/client/petstore/python-lazyImports/docs/InputAllOf.md index 45298f5308fc..32d4100ac9de 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/InputAllOf.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/InputAllOf.md @@ -15,14 +15,14 @@ from petstore_api.models.input_all_of import InputAllOf # TODO update the JSON string below json = "{}" # create an instance of InputAllOf from a JSON string -input_all_of_instance = InputAllOf.from_json(json) +input_all_of_instance = InputAllOf.model_validate_json(json) # print the JSON string representation of the object -print(InputAllOf.to_json()) +print(input_all_of_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -input_all_of_dict = input_all_of_instance.to_dict() +input_all_of_dict = input_all_of_instance.model_dump(by_alias=True) # create an instance of InputAllOf from a dict -input_all_of_from_dict = InputAllOf.from_dict(input_all_of_dict) +input_all_of_from_dict = InputAllOf.model_validate(input_all_of_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/IntOrString.md b/samples/openapi3/client/petstore/python-lazyImports/docs/IntOrString.md index b4070b9a8c79..ea8e06339493 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/IntOrString.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/IntOrString.md @@ -14,14 +14,14 @@ from petstore_api.models.int_or_string import IntOrString # TODO update the JSON string below json = "{}" # create an instance of IntOrString from a JSON string -int_or_string_instance = IntOrString.from_json(json) +int_or_string_instance = IntOrString.model_validate_json(json) # print the JSON string representation of the object -print(IntOrString.to_json()) +print(int_or_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -int_or_string_dict = int_or_string_instance.to_dict() +int_or_string_dict = int_or_string_instance.model_dump(by_alias=True) # create an instance of IntOrString from a dict -int_or_string_from_dict = IntOrString.from_dict(int_or_string_dict) +int_or_string_from_dict = IntOrString.model_validate(int_or_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ListClass.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ListClass.md index 01068b7d22c3..8bc905105efe 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ListClass.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ListClass.md @@ -15,14 +15,14 @@ from petstore_api.models.list_class import ListClass # TODO update the JSON string below json = "{}" # create an instance of ListClass from a JSON string -list_class_instance = ListClass.from_json(json) +list_class_instance = ListClass.model_validate_json(json) # print the JSON string representation of the object -print(ListClass.to_json()) +print(list_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -list_class_dict = list_class_instance.to_dict() +list_class_dict = list_class_instance.model_dump(by_alias=True) # create an instance of ListClass from a dict -list_class_from_dict = ListClass.from_dict(list_class_dict) +list_class_from_dict = ListClass.model_validate(list_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/MapOfArrayOfModel.md b/samples/openapi3/client/petstore/python-lazyImports/docs/MapOfArrayOfModel.md index 71a4ef66b682..acea13d9a9f5 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/MapOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/MapOfArrayOfModel.md @@ -15,14 +15,14 @@ from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel # TODO update the JSON string below json = "{}" # create an instance of MapOfArrayOfModel from a JSON string -map_of_array_of_model_instance = MapOfArrayOfModel.from_json(json) +map_of_array_of_model_instance = MapOfArrayOfModel.model_validate_json(json) # print the JSON string representation of the object -print(MapOfArrayOfModel.to_json()) +print(map_of_array_of_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -map_of_array_of_model_dict = map_of_array_of_model_instance.to_dict() +map_of_array_of_model_dict = map_of_array_of_model_instance.model_dump(by_alias=True) # create an instance of MapOfArrayOfModel from a dict -map_of_array_of_model_from_dict = MapOfArrayOfModel.from_dict(map_of_array_of_model_dict) +map_of_array_of_model_from_dict = MapOfArrayOfModel.model_validate(map_of_array_of_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/MapTest.md b/samples/openapi3/client/petstore/python-lazyImports/docs/MapTest.md index d04b82e9378c..fa4501d24286 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/MapTest.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/MapTest.md @@ -18,14 +18,14 @@ from petstore_api.models.map_test import MapTest # TODO update the JSON string below json = "{}" # create an instance of MapTest from a JSON string -map_test_instance = MapTest.from_json(json) +map_test_instance = MapTest.model_validate_json(json) # print the JSON string representation of the object -print(MapTest.to_json()) +print(map_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -map_test_dict = map_test_instance.to_dict() +map_test_dict = map_test_instance.model_dump(by_alias=True) # create an instance of MapTest from a dict -map_test_from_dict = MapTest.from_dict(map_test_dict) +map_test_from_dict = MapTest.model_validate(map_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-lazyImports/docs/MixedPropertiesAndAdditionalPropertiesClass.md index 84134317aefc..fb354956720a 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -17,14 +17,14 @@ from petstore_api.models.mixed_properties_and_additional_properties_class import # TODO update the JSON string below json = "{}" # create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string -mixed_properties_and_additional_properties_class_instance = MixedPropertiesAndAdditionalPropertiesClass.from_json(json) +mixed_properties_and_additional_properties_class_instance = MixedPropertiesAndAdditionalPropertiesClass.model_validate_json(json) # print the JSON string representation of the object -print(MixedPropertiesAndAdditionalPropertiesClass.to_json()) +print(mixed_properties_and_additional_properties_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -mixed_properties_and_additional_properties_class_dict = mixed_properties_and_additional_properties_class_instance.to_dict() +mixed_properties_and_additional_properties_class_dict = mixed_properties_and_additional_properties_class_instance.model_dump(by_alias=True) # create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict -mixed_properties_and_additional_properties_class_from_dict = MixedPropertiesAndAdditionalPropertiesClass.from_dict(mixed_properties_and_additional_properties_class_dict) +mixed_properties_and_additional_properties_class_from_dict = MixedPropertiesAndAdditionalPropertiesClass.model_validate(mixed_properties_and_additional_properties_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Model200Response.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Model200Response.md index 7fdbdefc6cec..6cffad7a6d3a 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Model200Response.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Model200Response.md @@ -17,14 +17,14 @@ from petstore_api.models.model200_response import Model200Response # TODO update the JSON string below json = "{}" # create an instance of Model200Response from a JSON string -model200_response_instance = Model200Response.from_json(json) +model200_response_instance = Model200Response.model_validate_json(json) # print the JSON string representation of the object -print(Model200Response.to_json()) +print(model200_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model200_response_dict = model200_response_instance.to_dict() +model200_response_dict = model200_response_instance.model_dump(by_alias=True) # create an instance of Model200Response from a dict -model200_response_from_dict = Model200Response.from_dict(model200_response_dict) +model200_response_from_dict = Model200Response.model_validate(model200_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ModelApiResponse.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ModelApiResponse.md index 5ddc0db2a0f3..4fdaa910bce4 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ModelApiResponse.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ModelApiResponse.md @@ -17,14 +17,14 @@ from petstore_api.models.model_api_response import ModelApiResponse # TODO update the JSON string below json = "{}" # create an instance of ModelApiResponse from a JSON string -model_api_response_instance = ModelApiResponse.from_json(json) +model_api_response_instance = ModelApiResponse.model_validate_json(json) # print the JSON string representation of the object -print(ModelApiResponse.to_json()) +print(model_api_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_api_response_dict = model_api_response_instance.to_dict() +model_api_response_dict = model_api_response_instance.model_dump(by_alias=True) # create an instance of ModelApiResponse from a dict -model_api_response_from_dict = ModelApiResponse.from_dict(model_api_response_dict) +model_api_response_from_dict = ModelApiResponse.model_validate(model_api_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ModelField.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ModelField.md index 9073b5dbdb00..43f064bd85a4 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ModelField.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ModelField.md @@ -15,14 +15,14 @@ from petstore_api.models.model_field import ModelField # TODO update the JSON string below json = "{}" # create an instance of ModelField from a JSON string -model_field_instance = ModelField.from_json(json) +model_field_instance = ModelField.model_validate_json(json) # print the JSON string representation of the object -print(ModelField.to_json()) +print(model_field_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_field_dict = model_field_instance.to_dict() +model_field_dict = model_field_instance.model_dump(by_alias=True) # create an instance of ModelField from a dict -model_field_from_dict = ModelField.from_dict(model_field_dict) +model_field_from_dict = ModelField.model_validate(model_field_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ModelReturn.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ModelReturn.md index 7d327053b0c3..236b2bb971ee 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ModelReturn.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ModelReturn.md @@ -16,14 +16,14 @@ from petstore_api.models.model_return import ModelReturn # TODO update the JSON string below json = "{}" # create an instance of ModelReturn from a JSON string -model_return_instance = ModelReturn.from_json(json) +model_return_instance = ModelReturn.model_validate_json(json) # print the JSON string representation of the object -print(ModelReturn.to_json()) +print(model_return_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_return_dict = model_return_instance.to_dict() +model_return_dict = model_return_instance.model_dump(by_alias=True) # create an instance of ModelReturn from a dict -model_return_from_dict = ModelReturn.from_dict(model_return_dict) +model_return_from_dict = ModelReturn.model_validate(model_return_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/MultiArrays.md b/samples/openapi3/client/petstore/python-lazyImports/docs/MultiArrays.md index fea5139e7e73..9cf5c5bb1faa 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/MultiArrays.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/MultiArrays.md @@ -16,14 +16,14 @@ from petstore_api.models.multi_arrays import MultiArrays # TODO update the JSON string below json = "{}" # create an instance of MultiArrays from a JSON string -multi_arrays_instance = MultiArrays.from_json(json) +multi_arrays_instance = MultiArrays.model_validate_json(json) # print the JSON string representation of the object -print(MultiArrays.to_json()) +print(multi_arrays_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -multi_arrays_dict = multi_arrays_instance.to_dict() +multi_arrays_dict = multi_arrays_instance.model_dump(by_alias=True) # create an instance of MultiArrays from a dict -multi_arrays_from_dict = MultiArrays.from_dict(multi_arrays_dict) +multi_arrays_from_dict = MultiArrays.model_validate(multi_arrays_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Name.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Name.md index 5a04ec1ada06..f9d2da4cccd2 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Name.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Name.md @@ -19,14 +19,14 @@ from petstore_api.models.name import Name # TODO update the JSON string below json = "{}" # create an instance of Name from a JSON string -name_instance = Name.from_json(json) +name_instance = Name.model_validate_json(json) # print the JSON string representation of the object -print(Name.to_json()) +print(name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -name_dict = name_instance.to_dict() +name_dict = name_instance.model_dump(by_alias=True) # create an instance of Name from a dict -name_from_dict = Name.from_dict(name_dict) +name_from_dict = Name.model_validate(name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/NullableClass.md b/samples/openapi3/client/petstore/python-lazyImports/docs/NullableClass.md index 0387dcc2c67a..cd84aa96eb19 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/NullableClass.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/NullableClass.md @@ -27,14 +27,14 @@ from petstore_api.models.nullable_class import NullableClass # TODO update the JSON string below json = "{}" # create an instance of NullableClass from a JSON string -nullable_class_instance = NullableClass.from_json(json) +nullable_class_instance = NullableClass.model_validate_json(json) # print the JSON string representation of the object -print(NullableClass.to_json()) +print(nullable_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -nullable_class_dict = nullable_class_instance.to_dict() +nullable_class_dict = nullable_class_instance.model_dump(by_alias=True) # create an instance of NullableClass from a dict -nullable_class_from_dict = NullableClass.from_dict(nullable_class_dict) +nullable_class_from_dict = NullableClass.model_validate(nullable_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/NullableProperty.md b/samples/openapi3/client/petstore/python-lazyImports/docs/NullableProperty.md index 30edaf4844b2..c0ef9b80fcb5 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/NullableProperty.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/NullableProperty.md @@ -16,14 +16,14 @@ from petstore_api.models.nullable_property import NullableProperty # TODO update the JSON string below json = "{}" # create an instance of NullableProperty from a JSON string -nullable_property_instance = NullableProperty.from_json(json) +nullable_property_instance = NullableProperty.model_validate_json(json) # print the JSON string representation of the object -print(NullableProperty.to_json()) +print(nullable_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -nullable_property_dict = nullable_property_instance.to_dict() +nullable_property_dict = nullable_property_instance.model_dump(by_alias=True) # create an instance of NullableProperty from a dict -nullable_property_from_dict = NullableProperty.from_dict(nullable_property_dict) +nullable_property_from_dict = NullableProperty.model_validate(nullable_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/NumberOnly.md b/samples/openapi3/client/petstore/python-lazyImports/docs/NumberOnly.md index 415dd25585d4..f1caf70ea2b7 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/NumberOnly.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/NumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.number_only import NumberOnly # TODO update the JSON string below json = "{}" # create an instance of NumberOnly from a JSON string -number_only_instance = NumberOnly.from_json(json) +number_only_instance = NumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(NumberOnly.to_json()) +print(number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -number_only_dict = number_only_instance.to_dict() +number_only_dict = number_only_instance.model_dump(by_alias=True) # create an instance of NumberOnly from a dict -number_only_from_dict = NumberOnly.from_dict(number_only_dict) +number_only_from_dict = NumberOnly.model_validate(number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ObjectToTestAdditionalProperties.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ObjectToTestAdditionalProperties.md index f6bc34c98e65..f201a9627dc3 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ObjectToTestAdditionalProperties.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ObjectToTestAdditionalProperties.md @@ -16,14 +16,14 @@ from petstore_api.models.object_to_test_additional_properties import ObjectToTes # TODO update the JSON string below json = "{}" # create an instance of ObjectToTestAdditionalProperties from a JSON string -object_to_test_additional_properties_instance = ObjectToTestAdditionalProperties.from_json(json) +object_to_test_additional_properties_instance = ObjectToTestAdditionalProperties.model_validate_json(json) # print the JSON string representation of the object -print(ObjectToTestAdditionalProperties.to_json()) +print(object_to_test_additional_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -object_to_test_additional_properties_dict = object_to_test_additional_properties_instance.to_dict() +object_to_test_additional_properties_dict = object_to_test_additional_properties_instance.model_dump(by_alias=True) # create an instance of ObjectToTestAdditionalProperties from a dict -object_to_test_additional_properties_from_dict = ObjectToTestAdditionalProperties.from_dict(object_to_test_additional_properties_dict) +object_to_test_additional_properties_from_dict = ObjectToTestAdditionalProperties.model_validate(object_to_test_additional_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ObjectWithDeprecatedFields.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ObjectWithDeprecatedFields.md index 6dbd2ace04f1..86cce93ba775 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ObjectWithDeprecatedFields.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ObjectWithDeprecatedFields.md @@ -18,14 +18,14 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecat # TODO update the JSON string below json = "{}" # create an instance of ObjectWithDeprecatedFields from a JSON string -object_with_deprecated_fields_instance = ObjectWithDeprecatedFields.from_json(json) +object_with_deprecated_fields_instance = ObjectWithDeprecatedFields.model_validate_json(json) # print the JSON string representation of the object -print(ObjectWithDeprecatedFields.to_json()) +print(object_with_deprecated_fields_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -object_with_deprecated_fields_dict = object_with_deprecated_fields_instance.to_dict() +object_with_deprecated_fields_dict = object_with_deprecated_fields_instance.model_dump(by_alias=True) # create an instance of ObjectWithDeprecatedFields from a dict -object_with_deprecated_fields_from_dict = ObjectWithDeprecatedFields.from_dict(object_with_deprecated_fields_dict) +object_with_deprecated_fields_from_dict = ObjectWithDeprecatedFields.model_validate(object_with_deprecated_fields_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/OneOfEnumString.md b/samples/openapi3/client/petstore/python-lazyImports/docs/OneOfEnumString.md index 1d385c092934..69f4f99d32e4 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/OneOfEnumString.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/OneOfEnumString.md @@ -15,14 +15,14 @@ from petstore_api.models.one_of_enum_string import OneOfEnumString # TODO update the JSON string below json = "{}" # create an instance of OneOfEnumString from a JSON string -one_of_enum_string_instance = OneOfEnumString.from_json(json) +one_of_enum_string_instance = OneOfEnumString.model_validate_json(json) # print the JSON string representation of the object -print(OneOfEnumString.to_json()) +print(one_of_enum_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -one_of_enum_string_dict = one_of_enum_string_instance.to_dict() +one_of_enum_string_dict = one_of_enum_string_instance.model_dump(by_alias=True) # create an instance of OneOfEnumString from a dict -one_of_enum_string_from_dict = OneOfEnumString.from_dict(one_of_enum_string_dict) +one_of_enum_string_from_dict = OneOfEnumString.model_validate(one_of_enum_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Order.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Order.md index 00526b8d04b9..f5410bc8d0f3 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Order.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Order.md @@ -20,14 +20,14 @@ from petstore_api.models.order import Order # TODO update the JSON string below json = "{}" # create an instance of Order from a JSON string -order_instance = Order.from_json(json) +order_instance = Order.model_validate_json(json) # print the JSON string representation of the object -print(Order.to_json()) +print(order_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -order_dict = order_instance.to_dict() +order_dict = order_instance.model_dump(by_alias=True) # create an instance of Order from a dict -order_from_dict = Order.from_dict(order_dict) +order_from_dict = Order.model_validate(order_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/OuterComposite.md b/samples/openapi3/client/petstore/python-lazyImports/docs/OuterComposite.md index c8242c2d2653..9df82e2abc87 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/OuterComposite.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/OuterComposite.md @@ -17,14 +17,14 @@ from petstore_api.models.outer_composite import OuterComposite # TODO update the JSON string below json = "{}" # create an instance of OuterComposite from a JSON string -outer_composite_instance = OuterComposite.from_json(json) +outer_composite_instance = OuterComposite.model_validate_json(json) # print the JSON string representation of the object -print(OuterComposite.to_json()) +print(outer_composite_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -outer_composite_dict = outer_composite_instance.to_dict() +outer_composite_dict = outer_composite_instance.model_dump(by_alias=True) # create an instance of OuterComposite from a dict -outer_composite_from_dict = OuterComposite.from_dict(outer_composite_dict) +outer_composite_from_dict = OuterComposite.model_validate(outer_composite_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/OuterObjectWithEnumProperty.md b/samples/openapi3/client/petstore/python-lazyImports/docs/OuterObjectWithEnumProperty.md index 6137dbd98da6..d23ccc3757bb 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/OuterObjectWithEnumProperty.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/OuterObjectWithEnumProperty.md @@ -16,14 +16,14 @@ from petstore_api.models.outer_object_with_enum_property import OuterObjectWithE # TODO update the JSON string below json = "{}" # create an instance of OuterObjectWithEnumProperty from a JSON string -outer_object_with_enum_property_instance = OuterObjectWithEnumProperty.from_json(json) +outer_object_with_enum_property_instance = OuterObjectWithEnumProperty.model_validate_json(json) # print the JSON string representation of the object -print(OuterObjectWithEnumProperty.to_json()) +print(outer_object_with_enum_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -outer_object_with_enum_property_dict = outer_object_with_enum_property_instance.to_dict() +outer_object_with_enum_property_dict = outer_object_with_enum_property_instance.model_dump(by_alias=True) # create an instance of OuterObjectWithEnumProperty from a dict -outer_object_with_enum_property_from_dict = OuterObjectWithEnumProperty.from_dict(outer_object_with_enum_property_dict) +outer_object_with_enum_property_from_dict = OuterObjectWithEnumProperty.model_validate(outer_object_with_enum_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Parent.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Parent.md index 7387f9250aad..21df089ea756 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Parent.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Parent.md @@ -15,14 +15,14 @@ from petstore_api.models.parent import Parent # TODO update the JSON string below json = "{}" # create an instance of Parent from a JSON string -parent_instance = Parent.from_json(json) +parent_instance = Parent.model_validate_json(json) # print the JSON string representation of the object -print(Parent.to_json()) +print(parent_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -parent_dict = parent_instance.to_dict() +parent_dict = parent_instance.model_dump(by_alias=True) # create an instance of Parent from a dict -parent_from_dict = Parent.from_dict(parent_dict) +parent_from_dict = Parent.model_validate(parent_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ParentWithOptionalDict.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ParentWithOptionalDict.md index bfc8688ea26f..a6ee19fd1a74 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ParentWithOptionalDict.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ParentWithOptionalDict.md @@ -15,14 +15,14 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict # TODO update the JSON string below json = "{}" # create an instance of ParentWithOptionalDict from a JSON string -parent_with_optional_dict_instance = ParentWithOptionalDict.from_json(json) +parent_with_optional_dict_instance = ParentWithOptionalDict.model_validate_json(json) # print the JSON string representation of the object -print(ParentWithOptionalDict.to_json()) +print(parent_with_optional_dict_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -parent_with_optional_dict_dict = parent_with_optional_dict_instance.to_dict() +parent_with_optional_dict_dict = parent_with_optional_dict_instance.model_dump(by_alias=True) # create an instance of ParentWithOptionalDict from a dict -parent_with_optional_dict_from_dict = ParentWithOptionalDict.from_dict(parent_with_optional_dict_dict) +parent_with_optional_dict_from_dict = ParentWithOptionalDict.model_validate(parent_with_optional_dict_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Pet.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Pet.md index 5329cf2fb925..179b71891d9d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Pet.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Pet.md @@ -20,14 +20,14 @@ from petstore_api.models.pet import Pet # TODO update the JSON string below json = "{}" # create an instance of Pet from a JSON string -pet_instance = Pet.from_json(json) +pet_instance = Pet.model_validate_json(json) # print the JSON string representation of the object -print(Pet.to_json()) +print(pet_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pet_dict = pet_instance.to_dict() +pet_dict = pet_instance.model_dump(by_alias=True) # create an instance of Pet from a dict -pet_from_dict = Pet.from_dict(pet_dict) +pet_from_dict = Pet.model_validate(pet_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Pig.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Pig.md index 625930676083..2e275198c547 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Pig.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Pig.md @@ -17,14 +17,14 @@ from petstore_api.models.pig import Pig # TODO update the JSON string below json = "{}" # create an instance of Pig from a JSON string -pig_instance = Pig.from_json(json) +pig_instance = Pig.model_validate_json(json) # print the JSON string representation of the object -print(Pig.to_json()) +print(pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pig_dict = pig_instance.to_dict() +pig_dict = pig_instance.model_dump(by_alias=True) # create an instance of Pig from a dict -pig_from_dict = Pig.from_dict(pig_dict) +pig_from_dict = Pig.model_validate(pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/PonySizes.md b/samples/openapi3/client/petstore/python-lazyImports/docs/PonySizes.md index ced44c872060..6bb28b418b6d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/PonySizes.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/PonySizes.md @@ -15,14 +15,14 @@ from petstore_api.models.pony_sizes import PonySizes # TODO update the JSON string below json = "{}" # create an instance of PonySizes from a JSON string -pony_sizes_instance = PonySizes.from_json(json) +pony_sizes_instance = PonySizes.model_validate_json(json) # print the JSON string representation of the object -print(PonySizes.to_json()) +print(pony_sizes_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pony_sizes_dict = pony_sizes_instance.to_dict() +pony_sizes_dict = pony_sizes_instance.model_dump(by_alias=True) # create an instance of PonySizes from a dict -pony_sizes_from_dict = PonySizes.from_dict(pony_sizes_dict) +pony_sizes_from_dict = PonySizes.model_validate(pony_sizes_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/PoopCleaning.md b/samples/openapi3/client/petstore/python-lazyImports/docs/PoopCleaning.md index 8f9c25e08316..3bf20593f929 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/PoopCleaning.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/PoopCleaning.md @@ -17,14 +17,14 @@ from petstore_api.models.poop_cleaning import PoopCleaning # TODO update the JSON string below json = "{}" # create an instance of PoopCleaning from a JSON string -poop_cleaning_instance = PoopCleaning.from_json(json) +poop_cleaning_instance = PoopCleaning.model_validate_json(json) # print the JSON string representation of the object -print(PoopCleaning.to_json()) +print(poop_cleaning_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -poop_cleaning_dict = poop_cleaning_instance.to_dict() +poop_cleaning_dict = poop_cleaning_instance.model_dump(by_alias=True) # create an instance of PoopCleaning from a dict -poop_cleaning_from_dict = PoopCleaning.from_dict(poop_cleaning_dict) +poop_cleaning_from_dict = PoopCleaning.model_validate(poop_cleaning_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/PrimitiveString.md b/samples/openapi3/client/petstore/python-lazyImports/docs/PrimitiveString.md index 85ceb632e167..a1a9a3dc81b6 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/PrimitiveString.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/PrimitiveString.md @@ -15,14 +15,14 @@ from petstore_api.models.primitive_string import PrimitiveString # TODO update the JSON string below json = "{}" # create an instance of PrimitiveString from a JSON string -primitive_string_instance = PrimitiveString.from_json(json) +primitive_string_instance = PrimitiveString.model_validate_json(json) # print the JSON string representation of the object -print(PrimitiveString.to_json()) +print(primitive_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -primitive_string_dict = primitive_string_instance.to_dict() +primitive_string_dict = primitive_string_instance.model_dump(by_alias=True) # create an instance of PrimitiveString from a dict -primitive_string_from_dict = PrimitiveString.from_dict(primitive_string_dict) +primitive_string_from_dict = PrimitiveString.model_validate(primitive_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/PropertyMap.md b/samples/openapi3/client/petstore/python-lazyImports/docs/PropertyMap.md index a55a0e5c6f01..5fcda1f7803d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/PropertyMap.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/PropertyMap.md @@ -15,14 +15,14 @@ from petstore_api.models.property_map import PropertyMap # TODO update the JSON string below json = "{}" # create an instance of PropertyMap from a JSON string -property_map_instance = PropertyMap.from_json(json) +property_map_instance = PropertyMap.model_validate_json(json) # print the JSON string representation of the object -print(PropertyMap.to_json()) +print(property_map_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -property_map_dict = property_map_instance.to_dict() +property_map_dict = property_map_instance.model_dump(by_alias=True) # create an instance of PropertyMap from a dict -property_map_from_dict = PropertyMap.from_dict(property_map_dict) +property_map_from_dict = PropertyMap.model_validate(property_map_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/PropertyNameCollision.md b/samples/openapi3/client/petstore/python-lazyImports/docs/PropertyNameCollision.md index 40c233670dd0..a4a8405fe847 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/PropertyNameCollision.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/PropertyNameCollision.md @@ -17,14 +17,14 @@ from petstore_api.models.property_name_collision import PropertyNameCollision # TODO update the JSON string below json = "{}" # create an instance of PropertyNameCollision from a JSON string -property_name_collision_instance = PropertyNameCollision.from_json(json) +property_name_collision_instance = PropertyNameCollision.model_validate_json(json) # print the JSON string representation of the object -print(PropertyNameCollision.to_json()) +print(property_name_collision_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -property_name_collision_dict = property_name_collision_instance.to_dict() +property_name_collision_dict = property_name_collision_instance.model_dump(by_alias=True) # create an instance of PropertyNameCollision from a dict -property_name_collision_from_dict = PropertyNameCollision.from_dict(property_name_collision_dict) +property_name_collision_from_dict = PropertyNameCollision.model_validate(property_name_collision_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python-lazyImports/docs/ReadOnlyFirst.md index 686ec5da41c9..e55fe102b673 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/ReadOnlyFirst.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/ReadOnlyFirst.md @@ -16,14 +16,14 @@ from petstore_api.models.read_only_first import ReadOnlyFirst # TODO update the JSON string below json = "{}" # create an instance of ReadOnlyFirst from a JSON string -read_only_first_instance = ReadOnlyFirst.from_json(json) +read_only_first_instance = ReadOnlyFirst.model_validate_json(json) # print the JSON string representation of the object -print(ReadOnlyFirst.to_json()) +print(read_only_first_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -read_only_first_dict = read_only_first_instance.to_dict() +read_only_first_dict = read_only_first_instance.model_dump(by_alias=True) # create an instance of ReadOnlyFirst from a dict -read_only_first_from_dict = ReadOnlyFirst.from_dict(read_only_first_dict) +read_only_first_from_dict = ReadOnlyFirst.model_validate(read_only_first_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/SecondCircularAllOfRef.md b/samples/openapi3/client/petstore/python-lazyImports/docs/SecondCircularAllOfRef.md index 65ebdd4c7e1d..47fb4daf97a4 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/SecondCircularAllOfRef.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/SecondCircularAllOfRef.md @@ -16,14 +16,14 @@ from petstore_api.models.second_circular_all_of_ref import SecondCircularAllOfRe # TODO update the JSON string below json = "{}" # create an instance of SecondCircularAllOfRef from a JSON string -second_circular_all_of_ref_instance = SecondCircularAllOfRef.from_json(json) +second_circular_all_of_ref_instance = SecondCircularAllOfRef.model_validate_json(json) # print the JSON string representation of the object -print(SecondCircularAllOfRef.to_json()) +print(second_circular_all_of_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -second_circular_all_of_ref_dict = second_circular_all_of_ref_instance.to_dict() +second_circular_all_of_ref_dict = second_circular_all_of_ref_instance.model_dump(by_alias=True) # create an instance of SecondCircularAllOfRef from a dict -second_circular_all_of_ref_from_dict = SecondCircularAllOfRef.from_dict(second_circular_all_of_ref_dict) +second_circular_all_of_ref_from_dict = SecondCircularAllOfRef.model_validate(second_circular_all_of_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/SecondRef.md b/samples/openapi3/client/petstore/python-lazyImports/docs/SecondRef.md index dfb1a0ac6db5..fa0b9f285e0c 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/SecondRef.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/SecondRef.md @@ -16,14 +16,14 @@ from petstore_api.models.second_ref import SecondRef # TODO update the JSON string below json = "{}" # create an instance of SecondRef from a JSON string -second_ref_instance = SecondRef.from_json(json) +second_ref_instance = SecondRef.model_validate_json(json) # print the JSON string representation of the object -print(SecondRef.to_json()) +print(second_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -second_ref_dict = second_ref_instance.to_dict() +second_ref_dict = second_ref_instance.model_dump(by_alias=True) # create an instance of SecondRef from a dict -second_ref_from_dict = SecondRef.from_dict(second_ref_dict) +second_ref_from_dict = SecondRef.model_validate(second_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/SelfReferenceModel.md b/samples/openapi3/client/petstore/python-lazyImports/docs/SelfReferenceModel.md index 208cdac04b6f..af3c77d0524b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/SelfReferenceModel.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/SelfReferenceModel.md @@ -16,14 +16,14 @@ from petstore_api.models.self_reference_model import SelfReferenceModel # TODO update the JSON string below json = "{}" # create an instance of SelfReferenceModel from a JSON string -self_reference_model_instance = SelfReferenceModel.from_json(json) +self_reference_model_instance = SelfReferenceModel.model_validate_json(json) # print the JSON string representation of the object -print(SelfReferenceModel.to_json()) +print(self_reference_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -self_reference_model_dict = self_reference_model_instance.to_dict() +self_reference_model_dict = self_reference_model_instance.model_dump(by_alias=True) # create an instance of SelfReferenceModel from a dict -self_reference_model_from_dict = SelfReferenceModel.from_dict(self_reference_model_dict) +self_reference_model_from_dict = SelfReferenceModel.model_validate(self_reference_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python-lazyImports/docs/SpecialModelName.md index 35303f34efd2..589dbeb14b94 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/SpecialModelName.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/SpecialModelName.md @@ -15,14 +15,14 @@ from petstore_api.models.special_model_name import SpecialModelName # TODO update the JSON string below json = "{}" # create an instance of SpecialModelName from a JSON string -special_model_name_instance = SpecialModelName.from_json(json) +special_model_name_instance = SpecialModelName.model_validate_json(json) # print the JSON string representation of the object -print(SpecialModelName.to_json()) +print(special_model_name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -special_model_name_dict = special_model_name_instance.to_dict() +special_model_name_dict = special_model_name_instance.model_dump(by_alias=True) # create an instance of SpecialModelName from a dict -special_model_name_from_dict = SpecialModelName.from_dict(special_model_name_dict) +special_model_name_from_dict = SpecialModelName.model_validate(special_model_name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/SpecialName.md b/samples/openapi3/client/petstore/python-lazyImports/docs/SpecialName.md index ccc550b16e33..19da9016451c 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/SpecialName.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/SpecialName.md @@ -17,14 +17,14 @@ from petstore_api.models.special_name import SpecialName # TODO update the JSON string below json = "{}" # create an instance of SpecialName from a JSON string -special_name_instance = SpecialName.from_json(json) +special_name_instance = SpecialName.model_validate_json(json) # print the JSON string representation of the object -print(SpecialName.to_json()) +print(special_name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -special_name_dict = special_name_instance.to_dict() +special_name_dict = special_name_instance.model_dump(by_alias=True) # create an instance of SpecialName from a dict -special_name_from_dict = SpecialName.from_dict(special_name_dict) +special_name_from_dict = SpecialName.model_validate(special_name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Tag.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Tag.md index 4106d9cfe5db..66339d14c875 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Tag.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Tag.md @@ -16,14 +16,14 @@ from petstore_api.models.tag import Tag # TODO update the JSON string below json = "{}" # create an instance of Tag from a JSON string -tag_instance = Tag.from_json(json) +tag_instance = Tag.model_validate_json(json) # print the JSON string representation of the object -print(Tag.to_json()) +print(tag_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tag_dict = tag_instance.to_dict() +tag_dict = tag_instance.model_dump(by_alias=True) # create an instance of Tag from a dict -tag_from_dict = Tag.from_dict(tag_dict) +tag_from_dict = Tag.model_validate(tag_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Task.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Task.md index 85fa2776a059..229ed6510a11 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Task.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Task.md @@ -17,14 +17,14 @@ from petstore_api.models.task import Task # TODO update the JSON string below json = "{}" # create an instance of Task from a JSON string -task_instance = Task.from_json(json) +task_instance = Task.model_validate_json(json) # print the JSON string representation of the object -print(Task.to_json()) +print(task_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -task_dict = task_instance.to_dict() +task_dict = task_instance.model_dump(by_alias=True) # create an instance of Task from a dict -task_from_dict = Task.from_dict(task_dict) +task_from_dict = Task.model_validate(task_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/TaskActivity.md b/samples/openapi3/client/petstore/python-lazyImports/docs/TaskActivity.md index e905a477292d..c025d32ba436 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/TaskActivity.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/TaskActivity.md @@ -17,14 +17,14 @@ from petstore_api.models.task_activity import TaskActivity # TODO update the JSON string below json = "{}" # create an instance of TaskActivity from a JSON string -task_activity_instance = TaskActivity.from_json(json) +task_activity_instance = TaskActivity.model_validate_json(json) # print the JSON string representation of the object -print(TaskActivity.to_json()) +print(task_activity_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -task_activity_dict = task_activity_instance.to_dict() +task_activity_dict = task_activity_instance.model_dump(by_alias=True) # create an instance of TaskActivity from a dict -task_activity_from_dict = TaskActivity.from_dict(task_activity_dict) +task_activity_from_dict = TaskActivity.model_validate(task_activity_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/TestErrorResponsesWithModel400Response.md b/samples/openapi3/client/petstore/python-lazyImports/docs/TestErrorResponsesWithModel400Response.md index be416bbad0f7..fed06705b55b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/TestErrorResponsesWithModel400Response.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/TestErrorResponsesWithModel400Response.md @@ -15,14 +15,14 @@ from petstore_api.models.test_error_responses_with_model400_response import Test # TODO update the JSON string below json = "{}" # create an instance of TestErrorResponsesWithModel400Response from a JSON string -test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.from_json(json) +test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.model_validate_json(json) # print the JSON string representation of the object -print(TestErrorResponsesWithModel400Response.to_json()) +print(test_error_responses_with_model400_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.to_dict() +test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.model_dump(by_alias=True) # create an instance of TestErrorResponsesWithModel400Response from a dict -test_error_responses_with_model400_response_from_dict = TestErrorResponsesWithModel400Response.from_dict(test_error_responses_with_model400_response_dict) +test_error_responses_with_model400_response_from_dict = TestErrorResponsesWithModel400Response.model_validate(test_error_responses_with_model400_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/TestErrorResponsesWithModel404Response.md b/samples/openapi3/client/petstore/python-lazyImports/docs/TestErrorResponsesWithModel404Response.md index 1c984f847bf1..8813e0792d22 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/TestErrorResponsesWithModel404Response.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/TestErrorResponsesWithModel404Response.md @@ -15,14 +15,14 @@ from petstore_api.models.test_error_responses_with_model404_response import Test # TODO update the JSON string below json = "{}" # create an instance of TestErrorResponsesWithModel404Response from a JSON string -test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.from_json(json) +test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.model_validate_json(json) # print the JSON string representation of the object -print(TestErrorResponsesWithModel404Response.to_json()) +print(test_error_responses_with_model404_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.to_dict() +test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.model_dump(by_alias=True) # create an instance of TestErrorResponsesWithModel404Response from a dict -test_error_responses_with_model404_response_from_dict = TestErrorResponsesWithModel404Response.from_dict(test_error_responses_with_model404_response_dict) +test_error_responses_with_model404_response_from_dict = TestErrorResponsesWithModel404Response.model_validate(test_error_responses_with_model404_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/TestInlineFreeformAdditionalPropertiesRequest.md b/samples/openapi3/client/petstore/python-lazyImports/docs/TestInlineFreeformAdditionalPropertiesRequest.md index 511132d689be..870cd8850e6b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/TestInlineFreeformAdditionalPropertiesRequest.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -15,14 +15,14 @@ from petstore_api.models.test_inline_freeform_additional_properties_request impo # TODO update the JSON string below json = "{}" # create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string -test_inline_freeform_additional_properties_request_instance = TestInlineFreeformAdditionalPropertiesRequest.from_json(json) +test_inline_freeform_additional_properties_request_instance = TestInlineFreeformAdditionalPropertiesRequest.model_validate_json(json) # print the JSON string representation of the object -print(TestInlineFreeformAdditionalPropertiesRequest.to_json()) +print(test_inline_freeform_additional_properties_request_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_inline_freeform_additional_properties_request_dict = test_inline_freeform_additional_properties_request_instance.to_dict() +test_inline_freeform_additional_properties_request_dict = test_inline_freeform_additional_properties_request_instance.model_dump(by_alias=True) # create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict -test_inline_freeform_additional_properties_request_from_dict = TestInlineFreeformAdditionalPropertiesRequest.from_dict(test_inline_freeform_additional_properties_request_dict) +test_inline_freeform_additional_properties_request_from_dict = TestInlineFreeformAdditionalPropertiesRequest.model_validate(test_inline_freeform_additional_properties_request_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/TestModelWithEnumDefault.md b/samples/openapi3/client/petstore/python-lazyImports/docs/TestModelWithEnumDefault.md index 7d46e86deba4..1f63056fe0f1 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/TestModelWithEnumDefault.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/TestModelWithEnumDefault.md @@ -19,14 +19,14 @@ from petstore_api.models.test_model_with_enum_default import TestModelWithEnumDe # TODO update the JSON string below json = "{}" # create an instance of TestModelWithEnumDefault from a JSON string -test_model_with_enum_default_instance = TestModelWithEnumDefault.from_json(json) +test_model_with_enum_default_instance = TestModelWithEnumDefault.model_validate_json(json) # print the JSON string representation of the object -print(TestModelWithEnumDefault.to_json()) +print(test_model_with_enum_default_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_model_with_enum_default_dict = test_model_with_enum_default_instance.to_dict() +test_model_with_enum_default_dict = test_model_with_enum_default_instance.model_dump(by_alias=True) # create an instance of TestModelWithEnumDefault from a dict -test_model_with_enum_default_from_dict = TestModelWithEnumDefault.from_dict(test_model_with_enum_default_dict) +test_model_with_enum_default_from_dict = TestModelWithEnumDefault.model_validate(test_model_with_enum_default_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/TestObjectForMultipartRequestsRequestMarker.md b/samples/openapi3/client/petstore/python-lazyImports/docs/TestObjectForMultipartRequestsRequestMarker.md index ff0ca9ee00ac..bb685d44835a 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/TestObjectForMultipartRequestsRequestMarker.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/TestObjectForMultipartRequestsRequestMarker.md @@ -15,14 +15,14 @@ from petstore_api.models.test_object_for_multipart_requests_request_marker impor # TODO update the JSON string below json = "{}" # create an instance of TestObjectForMultipartRequestsRequestMarker from a JSON string -test_object_for_multipart_requests_request_marker_instance = TestObjectForMultipartRequestsRequestMarker.from_json(json) +test_object_for_multipart_requests_request_marker_instance = TestObjectForMultipartRequestsRequestMarker.model_validate_json(json) # print the JSON string representation of the object -print(TestObjectForMultipartRequestsRequestMarker.to_json()) +print(test_object_for_multipart_requests_request_marker_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_object_for_multipart_requests_request_marker_dict = test_object_for_multipart_requests_request_marker_instance.to_dict() +test_object_for_multipart_requests_request_marker_dict = test_object_for_multipart_requests_request_marker_instance.model_dump(by_alias=True) # create an instance of TestObjectForMultipartRequestsRequestMarker from a dict -test_object_for_multipart_requests_request_marker_from_dict = TestObjectForMultipartRequestsRequestMarker.from_dict(test_object_for_multipart_requests_request_marker_dict) +test_object_for_multipart_requests_request_marker_from_dict = TestObjectForMultipartRequestsRequestMarker.model_validate(test_object_for_multipart_requests_request_marker_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/Tiger.md b/samples/openapi3/client/petstore/python-lazyImports/docs/Tiger.md index f1cf2133f0f7..90c7d8770979 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/Tiger.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/Tiger.md @@ -15,14 +15,14 @@ from petstore_api.models.tiger import Tiger # TODO update the JSON string below json = "{}" # create an instance of Tiger from a JSON string -tiger_instance = Tiger.from_json(json) +tiger_instance = Tiger.model_validate_json(json) # print the JSON string representation of the object -print(Tiger.to_json()) +print(tiger_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tiger_dict = tiger_instance.to_dict() +tiger_dict = tiger_instance.model_dump(by_alias=True) # create an instance of Tiger from a dict -tiger_from_dict = Tiger.from_dict(tiger_dict) +tiger_from_dict = Tiger.model_validate(tiger_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/UnnamedDictWithAdditionalModelListProperties.md b/samples/openapi3/client/petstore/python-lazyImports/docs/UnnamedDictWithAdditionalModelListProperties.md index 68cd00ab0a7a..0b411bf5df7b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/UnnamedDictWithAdditionalModelListProperties.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/UnnamedDictWithAdditionalModelListProperties.md @@ -15,14 +15,14 @@ from petstore_api.models.unnamed_dict_with_additional_model_list_properties impo # TODO update the JSON string below json = "{}" # create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string -unnamed_dict_with_additional_model_list_properties_instance = UnnamedDictWithAdditionalModelListProperties.from_json(json) +unnamed_dict_with_additional_model_list_properties_instance = UnnamedDictWithAdditionalModelListProperties.model_validate_json(json) # print the JSON string representation of the object -print(UnnamedDictWithAdditionalModelListProperties.to_json()) +print(unnamed_dict_with_additional_model_list_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -unnamed_dict_with_additional_model_list_properties_dict = unnamed_dict_with_additional_model_list_properties_instance.to_dict() +unnamed_dict_with_additional_model_list_properties_dict = unnamed_dict_with_additional_model_list_properties_instance.model_dump(by_alias=True) # create an instance of UnnamedDictWithAdditionalModelListProperties from a dict -unnamed_dict_with_additional_model_list_properties_from_dict = UnnamedDictWithAdditionalModelListProperties.from_dict(unnamed_dict_with_additional_model_list_properties_dict) +unnamed_dict_with_additional_model_list_properties_from_dict = UnnamedDictWithAdditionalModelListProperties.model_validate(unnamed_dict_with_additional_model_list_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/UnnamedDictWithAdditionalStringListProperties.md b/samples/openapi3/client/petstore/python-lazyImports/docs/UnnamedDictWithAdditionalStringListProperties.md index 045b0e22ad09..def639720586 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/UnnamedDictWithAdditionalStringListProperties.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/UnnamedDictWithAdditionalStringListProperties.md @@ -15,14 +15,14 @@ from petstore_api.models.unnamed_dict_with_additional_string_list_properties imp # TODO update the JSON string below json = "{}" # create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string -unnamed_dict_with_additional_string_list_properties_instance = UnnamedDictWithAdditionalStringListProperties.from_json(json) +unnamed_dict_with_additional_string_list_properties_instance = UnnamedDictWithAdditionalStringListProperties.model_validate_json(json) # print the JSON string representation of the object -print(UnnamedDictWithAdditionalStringListProperties.to_json()) +print(unnamed_dict_with_additional_string_list_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -unnamed_dict_with_additional_string_list_properties_dict = unnamed_dict_with_additional_string_list_properties_instance.to_dict() +unnamed_dict_with_additional_string_list_properties_dict = unnamed_dict_with_additional_string_list_properties_instance.model_dump(by_alias=True) # create an instance of UnnamedDictWithAdditionalStringListProperties from a dict -unnamed_dict_with_additional_string_list_properties_from_dict = UnnamedDictWithAdditionalStringListProperties.from_dict(unnamed_dict_with_additional_string_list_properties_dict) +unnamed_dict_with_additional_string_list_properties_from_dict = UnnamedDictWithAdditionalStringListProperties.model_validate(unnamed_dict_with_additional_string_list_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python-lazyImports/docs/UploadFileWithAdditionalPropertiesRequestObject.md index 141027780371..35be1642e660 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/UploadFileWithAdditionalPropertiesRequestObject.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -16,14 +16,14 @@ from petstore_api.models.upload_file_with_additional_properties_request_object i # TODO update the JSON string below json = "{}" # create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string -upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.from_json(json) +upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.model_validate_json(json) # print the JSON string representation of the object -print(UploadFileWithAdditionalPropertiesRequestObject.to_json()) +print(upload_file_with_additional_properties_request_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.to_dict() +upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.model_dump(by_alias=True) # create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict -upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.from_dict(upload_file_with_additional_properties_request_object_dict) +upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.model_validate(upload_file_with_additional_properties_request_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/User.md b/samples/openapi3/client/petstore/python-lazyImports/docs/User.md index c45d26d27043..8f4ae3d04712 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/User.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/User.md @@ -22,14 +22,14 @@ from petstore_api.models.user import User # TODO update the JSON string below json = "{}" # create an instance of User from a JSON string -user_instance = User.from_json(json) +user_instance = User.model_validate_json(json) # print the JSON string representation of the object -print(User.to_json()) +print(user_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -user_dict = user_instance.to_dict() +user_dict = user_instance.model_dump(by_alias=True) # create an instance of User from a dict -user_from_dict = User.from_dict(user_dict) +user_from_dict = User.model_validate(user_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/docs/WithNestedOneOf.md b/samples/openapi3/client/petstore/python-lazyImports/docs/WithNestedOneOf.md index e7bbbc28fc2d..12d648bb920d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/docs/WithNestedOneOf.md +++ b/samples/openapi3/client/petstore/python-lazyImports/docs/WithNestedOneOf.md @@ -17,14 +17,14 @@ from petstore_api.models.with_nested_one_of import WithNestedOneOf # TODO update the JSON string below json = "{}" # create an instance of WithNestedOneOf from a JSON string -with_nested_one_of_instance = WithNestedOneOf.from_json(json) +with_nested_one_of_instance = WithNestedOneOf.model_validate_json(json) # print the JSON string representation of the object -print(WithNestedOneOf.to_json()) +print(with_nested_one_of_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -with_nested_one_of_dict = with_nested_one_of_instance.to_dict() +with_nested_one_of_dict = with_nested_one_of_instance.model_dump(by_alias=True) # create an instance of WithNestedOneOf from a dict -with_nested_one_of_from_dict = WithNestedOneOf.from_dict(with_nested_one_of_dict) +with_nested_one_of_from_dict = WithNestedOneOf.model_validate(with_nested_one_of_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/api_client.py index 1e2c74b334c8..666d00d5f216 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/api_client.py @@ -714,7 +714,7 @@ def __deserialize_file(self, response): content_disposition ) assert m is not None, "Unexpected 'content-disposition' header value" - filename = m.group(1) + filename = os.path.basename(m.group(1)) # Strip any directory traversal path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_any_type.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_any_type.py index 291b5e55e353..d3c2e0c15c8d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_any_type.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_any_type.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesAnyType(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesAnyType(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesAnyType from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesAnyType from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_class.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_class.py index 220f23a423b4..98a41160b3b2 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_class.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesClass(BaseModel): """ @@ -38,65 +39,27 @@ class AdditionalPropertiesClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "map_property": obj.get("map_property"), - "map_of_map_property": obj.get("map_of_map_property") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_object.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_object.py index 00707c3c4818..4484e38c8bef 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_object.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesObject(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_with_description_only.py index d8049b519ed0..0dd3de45f5d3 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_with_description_only.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/additional_properties_with_description_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesWithDescriptionOnly(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesWithDescriptionOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesWithDescriptionOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/all_of_super_model.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/all_of_super_model.py index b63bba1206a2..fb0462733d3b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/all_of_super_model.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/all_of_super_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AllOfSuperModel(BaseModel): """ @@ -37,64 +38,27 @@ class AllOfSuperModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AllOfSuperModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AllOfSuperModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/all_of_with_single_ref.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/all_of_with_single_ref.py index e3fa084b0709..41022273145a 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/all_of_with_single_ref.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/all_of_with_single_ref.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.single_ref_type import SingleRefType from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AllOfWithSingleRef(BaseModel): """ @@ -39,65 +40,27 @@ class AllOfWithSingleRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AllOfWithSingleRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AllOfWithSingleRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "username": obj.get("username"), - "SingleRefType": obj.get("SingleRefType") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/animal.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/animal.py index 131ad8d0ed60..9a785d57c411 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/animal.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/animal.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -61,59 +62,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[Cat, Dog]]: - """Create an instance of Animal from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[Cat, Dog]]: - """Create an instance of Animal from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'Cat': - return import_module("petstore_api.models.cat").Cat.from_dict(obj) - if object_type == 'Dog': - return import_module("petstore_api.models.dog").Dog.from_dict(obj) - - raise ValueError("Animal failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_color.py index f6d277e79498..b86b03be3591 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_color.py @@ -13,8 +13,6 @@ from __future__ import annotations -from inspect import getfullargspec -import json import pprint import re # noqa: F401 from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator @@ -22,135 +20,56 @@ from typing_extensions import Annotated from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self -from pydantic import Field +from pydantic import Field, RootModel ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] -class AnyOfColor(BaseModel): + +class AnyOfColor(RootModel[Union[List[int], str]]): """ Any of RGB array, RGBA array, or hex string. """ - # data type: List[int] - anyof_schema_1_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=3, max_length=3)]] = Field(default=None, description="RGB three element array with values 0-255.") - # data type: List[int] - anyof_schema_2_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=4, max_length=4)]] = Field(default=None, description="RGBA four element array with values 0-255.") - # data type: str - anyof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") - if TYPE_CHECKING: - actual_instance: Optional[Union[List[int], str]] = None - else: - actual_instance: Any = None - any_of_schemas: Set[str] = { "List[int]", "str" } - - model_config = { - "validate_assignment": True, - "protected_namespaces": (), - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - instance = AnyOfColor.model_construct() - error_messages = [] - # validate data type: List[int] - try: - instance.anyof_schema_1_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: List[int] - try: - instance.anyof_schema_2_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.anyof_schema_3_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return v + root: Union[List[int], str] = Field( + ... + ) + + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ + + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod def from_dict(cls, obj: Dict[str, Any]) -> Self: - return cls.from_json(json.dumps(obj)) + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - # deserialize data into List[int] - try: - # validation - instance.anyof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_1_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into List[int] - try: - # validation - instance.anyof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_2_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.anyof_schema_3_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_3_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) + return self.model_dump_json(by_alias=True, exclude_none=True) - def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) + diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_pig.py index c949e136f415..a632d3c382d6 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/any_of_pig.py @@ -13,8 +13,6 @@ from __future__ import annotations -from inspect import getfullargspec -import json import pprint import re # noqa: F401 from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator @@ -23,112 +21,56 @@ from petstore_api.models.danish_pig import DanishPig from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self -from pydantic import Field +from pydantic import Field, RootModel ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] -class AnyOfPig(BaseModel): + +class AnyOfPig(RootModel[Union[BasquePig, DanishPig]]): """ AnyOfPig """ - # data type: BasquePig - anyof_schema_1_validator: Optional[BasquePig] = None - # data type: DanishPig - anyof_schema_2_validator: Optional[DanishPig] = None - if TYPE_CHECKING: - actual_instance: Optional[Union[BasquePig, DanishPig]] = None - else: - actual_instance: Any = None - any_of_schemas: Set[str] = { "BasquePig", "DanishPig" } - - model_config = { - "validate_assignment": True, - "protected_namespaces": (), - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - instance = AnyOfPig.model_construct() - error_messages = [] - # validate data type: BasquePig - if not isinstance(v, BasquePig): - error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`") - else: - return v - - # validate data type: DanishPig - if not isinstance(v, DanishPig): - error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`") - else: - return v - - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return v + root: Union[BasquePig, DanishPig] = Field( + ... + ) + + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ + + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod def from_dict(cls, obj: Dict[str, Any]) -> Self: - return cls.from_json(json.dumps(obj)) + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - # anyof_schema_1_validator: Optional[BasquePig] = None - try: - instance.actual_instance = BasquePig.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # anyof_schema_2_validator: Optional[DanishPig] = None - try: - instance.actual_instance = DanishPig.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) + return self.model_dump_json(by_alias=True, exclude_none=True) - def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) + diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_array_of_model.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_array_of_model.py index 80d4aa689164..17afbb8e1cb5 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_array_of_model.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfArrayOfModel(BaseModel): """ @@ -38,76 +39,27 @@ class ArrayOfArrayOfModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in another_property (list of list) - _items = [] - if self.another_property: - for _item_another_property in self.another_property: - if _item_another_property: - _items.append( - [_inner_item.to_dict() for _inner_item in _item_another_property if _inner_item is not None] - ) - _dict['another_property'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "another_property": [ - [Tag.from_dict(_inner_item) for _inner_item in _item] - for _item in obj["another_property"] - ] if obj.get("another_property") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_array_of_number_only.py index 847ae88c4ffa..c3d9327871dc 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_array_of_number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictFloat from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfArrayOfNumberOnly(BaseModel): """ @@ -37,64 +38,27 @@ class ArrayOfArrayOfNumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfNumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfNumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "ArrayArrayNumber": obj.get("ArrayArrayNumber") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_number_only.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_number_only.py index 4634914c33eb..7fdbf469baba 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_of_number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictFloat from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfNumberOnly(BaseModel): """ @@ -37,64 +38,27 @@ class ArrayOfNumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfNumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfNumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "ArrayNumber": obj.get("ArrayNumber") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_test.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_test.py index 9cadd4e7beb7..277694149dd2 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_test.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/array_test.py @@ -22,7 +22,8 @@ from typing_extensions import Annotated from petstore_api.models.read_only_first import ReadOnlyFirst from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayTest(BaseModel): """ @@ -42,79 +43,27 @@ class ArrayTest(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in array_array_of_model (list of list) - _items = [] - if self.array_array_of_model: - for _item_array_array_of_model in self.array_array_of_model: - if _item_array_array_of_model: - _items.append( - [_inner_item.to_dict() for _inner_item in _item_array_array_of_model if _inner_item is not None] - ) - _dict['array_array_of_model'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "array_of_string": obj.get("array_of_string"), - "array_of_nullable_float": obj.get("array_of_nullable_float"), - "array_array_of_integer": obj.get("array_array_of_integer"), - "array_array_of_model": [ - [ReadOnlyFirst.from_dict(_inner_item) for _inner_item in _item] - for _item in obj["array_array_of_model"] - ] if obj.get("array_array_of_model") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/base_discriminator.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/base_discriminator.py index 40b49a2fca7f..c7853a6c9be8 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/base_discriminator.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/base_discriminator.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -60,59 +61,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[PrimitiveString, Info]]: - """Create an instance of BaseDiscriminator from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[PrimitiveString, Info]]: - """Create an instance of BaseDiscriminator from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'PrimitiveString': - return import_module("petstore_api.models.primitive_string").PrimitiveString.from_dict(obj) - if object_type == 'Info': - return import_module("petstore_api.models.info").Info.from_dict(obj) - - raise ValueError("BaseDiscriminator failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/basque_pig.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/basque_pig.py index 4a5b9e3bcb9d..f88eb2e92af0 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/basque_pig.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/basque_pig.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class BasquePig(BaseModel): """ @@ -38,65 +39,27 @@ class BasquePig(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of BasquePig from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of BasquePig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/bathing.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/bathing.py index 289d9d4670ab..bac0c4a55e6b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/bathing.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/bathing.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Bathing(BaseModel): """ Bathing """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning_deep'] = Field( + ..., + description="task_name of the Bathing", + alias="task_name" + ) + function_name: Literal['care_nourish'] = Field( + ..., + description="function_name of the Bathing", + alias="function_name" + ) content: StrictStr additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -53,66 +62,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Bathing from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Bathing from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/capitalization.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/capitalization.py index d98aa21e532d..47eaa639b7f7 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/capitalization.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/capitalization.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Capitalization(BaseModel): """ @@ -42,69 +43,27 @@ class Capitalization(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Capitalization from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Capitalization from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "smallCamel": obj.get("smallCamel"), - "CapitalCamel": obj.get("CapitalCamel"), - "small_Snake": obj.get("small_Snake"), - "Capital_Snake": obj.get("Capital_Snake"), - "SCA_ETH_Flow_Points": obj.get("SCA_ETH_Flow_Points"), - "ATT_NAME": obj.get("ATT_NAME") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/cat.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/cat.py index 86002178c904..a982c0e5048d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/cat.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/cat.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Cat(Animal): """ @@ -38,66 +39,27 @@ class Cat(Animal): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Cat from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Cat from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") if obj.get("color") is not None else 'red', - "declawed": obj.get("declawed") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/category.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/category.py index c659f1845726..9d872fde9d05 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/category.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/category.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Category(BaseModel): """ @@ -38,65 +39,27 @@ class Category(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Category from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Category from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") if obj.get("name") is not None else 'default-name' - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/circular_all_of_ref.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/circular_all_of_ref.py index d3b6cbe57ea1..cc547e3c1122 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/circular_all_of_ref.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/circular_all_of_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CircularAllOfRef(BaseModel): """ @@ -38,73 +39,28 @@ class CircularAllOfRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CircularAllOfRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in second_circular_all_of_ref (list) - _items = [] - if self.second_circular_all_of_ref: - for _item_second_circular_all_of_ref in self.second_circular_all_of_ref: - if _item_second_circular_all_of_ref: - _items.append(_item_second_circular_all_of_ref.to_dict()) - _dict['secondCircularAllOfRef'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CircularAllOfRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name"), - "secondCircularAllOfRef": [SecondCircularAllOfRef.from_dict(_item) for _item in obj["secondCircularAllOfRef"]] if obj.get("secondCircularAllOfRef") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.second_circular_all_of_ref import SecondCircularAllOfRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/circular_reference_model.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/circular_reference_model.py index 8c118f3c09b2..7524f9ee4b71 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/circular_reference_model.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/circular_reference_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CircularReferenceModel(BaseModel): """ @@ -38,69 +39,28 @@ class CircularReferenceModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CircularReferenceModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested - if self.nested: - _dict['nested'] = self.nested.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CircularReferenceModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested": FirstRef.from_dict(obj["nested"]) if obj.get("nested") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.first_ref import FirstRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/class_model.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/class_model.py index 06f8f91b83cb..24e5f75ac3f1 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/class_model.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/class_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ClassModel(BaseModel): """ @@ -37,64 +38,27 @@ class ClassModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ClassModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ClassModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_class": obj.get("_class") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/client.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/client.py index d3376d62357b..fb089635fd0a 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/client.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/client.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Client(BaseModel): """ @@ -37,64 +38,27 @@ class Client(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Client from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Client from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "client": obj.get("client") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/color.py index bb740fb597d4..5197fe58ecc6 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/color.py @@ -18,150 +18,55 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional from typing_extensions import Annotated -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] -class Color(BaseModel): +class Color(RootModel[Union[List[int], str]]): """ RGB array, RGBA array, or hex string. """ - # data type: List[int] - oneof_schema_1_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=3, max_length=3)]] = Field(default=None, description="RGB three element array with values 0-255.") - # data type: List[int] - oneof_schema_2_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=4, max_length=4)]] = Field(default=None, description="RGBA four element array with values 0-255.") - # data type: str - oneof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") - actual_instance: Optional[Union[List[int], str]] = None - one_of_schemas: Set[str] = { "List[int]", "str" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[List[int], str, None] = Field( + None ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - if v is None: - return v - - instance = Color.model_construct() - error_messages = [] - match = 0 - # validate data type: List[int] - try: - instance.oneof_schema_1_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: List[int] - try: - instance.oneof_schema_2_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.oneof_schema_3_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: Optional[str]) -> Self: + def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - if json_str is None: - return instance - - error_messages = [] - match = 0 - - # deserialize data into List[int] - try: - # validation - instance.oneof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_1_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into List[int] - try: - # validation - instance.oneof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_2_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.oneof_schema_3_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_3_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/creature.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/creature.py index ce6a70327b1a..06debc61d646 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/creature.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/creature.py @@ -22,7 +22,8 @@ from typing import Any, ClassVar, Dict, List, Union from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -61,60 +62,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[HuntingDog]]: - """Create an instance of Creature from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of info - if self.info: - _dict['info'] = self.info.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[HuntingDog]]: - """Create an instance of Creature from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'HuntingDog': - return import_module("petstore_api.models.hunting_dog").HuntingDog.from_dict(obj) - - raise ValueError("Creature failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/creature_info.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/creature_info.py index e7fef158a580..d7b41b7b9580 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/creature_info.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/creature_info.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CreatureInfo(BaseModel): """ @@ -37,64 +38,27 @@ class CreatureInfo(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CreatureInfo from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CreatureInfo from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/danish_pig.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/danish_pig.py index df4a80d33908..3fb64cdaf2c8 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/danish_pig.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/danish_pig.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DanishPig(BaseModel): """ @@ -38,65 +39,27 @@ class DanishPig(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DanishPig from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DanishPig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "size": obj.get("size") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/deprecated_object.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/deprecated_object.py index ad0ec89a5b7a..2194c3231637 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/deprecated_object.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/deprecated_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DeprecatedObject(BaseModel): """ @@ -37,64 +38,27 @@ class DeprecatedObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DeprecatedObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DeprecatedObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/discriminator_all_of_sub.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/discriminator_all_of_sub.py index 9723d2e28c74..f2a1fdfe4a61 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/discriminator_all_of_sub.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/discriminator_all_of_sub.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List from petstore_api.models.discriminator_all_of_super import DiscriminatorAllOfSuper from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DiscriminatorAllOfSub(DiscriminatorAllOfSuper): """ @@ -37,64 +38,27 @@ class DiscriminatorAllOfSub(DiscriminatorAllOfSuper): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DiscriminatorAllOfSub from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DiscriminatorAllOfSub from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "elementType": obj.get("elementType") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/discriminator_all_of_super.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/discriminator_all_of_super.py index e3d62831065a..ec0647d296c4 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/discriminator_all_of_super.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/discriminator_all_of_super.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -59,57 +60,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[DiscriminatorAllOfSub]]: - """Create an instance of DiscriminatorAllOfSuper from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[DiscriminatorAllOfSub]]: - """Create an instance of DiscriminatorAllOfSuper from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'DiscriminatorAllOfSub': - return import_module("petstore_api.models.discriminator_all_of_sub").DiscriminatorAllOfSub.from_dict(obj) - - raise ValueError("DiscriminatorAllOfSuper failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/dog.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/dog.py index cde0f5d27e0c..de660986c36c 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/dog.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/dog.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Dog(Animal): """ @@ -38,66 +39,27 @@ class Dog(Animal): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Dog from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Dog from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") if obj.get("color") is not None else 'red', - "breed": obj.get("breed") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/dummy_model.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/dummy_model.py index 47fdb81a397a..6eaf6cd615de 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/dummy_model.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/dummy_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DummyModel(BaseModel): """ @@ -38,69 +39,28 @@ class DummyModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DummyModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of self_ref - if self.self_ref: - _dict['self_ref'] = self.self_ref.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DummyModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "self_ref": SelfReferenceModel.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.self_reference_model import SelfReferenceModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_arrays.py index 17d3e0afd2df..315c4c93abce 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_arrays.py @@ -20,14 +20,21 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumArrays(BaseModel): """ EnumArrays """ # noqa: E501 - just_symbol: Optional[StrictStr] = None - array_enum: Optional[List[StrictStr]] = None + just_symbol: Optional[Literal['>=', '$']] = Field( + None, + description="just_symbol of the EnumArrays" + ) + array_enum: Optional[List[Literal['fish', 'crab']]] = Field( + None, + description="array_enum of the EnumArrays" + ) additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["just_symbol", "array_enum"] @@ -59,65 +66,27 @@ def array_enum_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumArrays from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumArrays from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "just_symbol": obj.get("just_symbol"), - "array_enum": obj.get("array_enum") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_ref_with_default_value.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_ref_with_default_value.py index d864e80d0a73..d697019cf974 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_ref_with_default_value.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_ref_with_default_value.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.data_output_format import DataOutputFormat from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumRefWithDefaultValue(BaseModel): """ @@ -38,64 +39,27 @@ class EnumRefWithDefaultValue(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumRefWithDefaultValue from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumRefWithDefaultValue from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "report_format": obj.get("report_format") if obj.get("report_format") is not None else DataOutputFormat.JSON - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_test.py index d39c2c95775e..d273604b81bc 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/enum_test.py @@ -26,19 +26,43 @@ from petstore_api.models.outer_enum_integer import OuterEnumInteger from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumTest(BaseModel): """ EnumTest """ # noqa: E501 - enum_string: Optional[StrictStr] = None - enum_string_required: StrictStr - enum_integer_default: Optional[StrictInt] = 5 - enum_integer: Optional[StrictInt] = None - enum_number: Optional[StrictFloat] = None - enum_string_single_member: Optional[StrictStr] = None - enum_integer_single_member: Optional[StrictInt] = None + enum_string: Optional[Literal['UPPER', 'lower', '']] = Field( + None, + description="enum_string of the EnumTest" + ) + enum_string_required: Literal['UPPER', 'lower', ''] = Field( + ..., + description="enum_string_required of the EnumTest" + ) + enum_integer_default: Optional[Literal[1, 5, 14]] = Field( + None, + description="enum_integer_default of the EnumTest" + ) + enum_integer: Optional[Literal[1, -1]] = Field( + None, + description="enum_integer of the EnumTest" + ) + enum_number: Optional[Literal[1.1, -1.2]] = Field( + None, + description="enum_number of the EnumTest" + ) + enum_string_single_member: Literal['abc'] = Field( + None, + description="enum_string_single_member of the EnumTest", + alias="enum_string_single_member" + ) + enum_integer_single_member: Literal['100'] = Field( + None, + description="enum_integer_single_member of the EnumTest", + alias="enum_integer_single_member" + ) outer_enum: Optional[OuterEnum] = Field(default=None, alias="outerEnum") outer_enum_integer: Optional[OuterEnumInteger] = Field(default=None, alias="outerEnumInteger") outer_enum_default_value: Optional[OuterEnumDefaultValue] = Field(default=OuterEnumDefaultValue.PLACED, alias="outerEnumDefaultValue") @@ -122,81 +146,27 @@ def enum_integer_single_member_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if outer_enum (nullable) is None - # and model_fields_set contains the field - if self.outer_enum is None and "outer_enum" in self.model_fields_set: - _dict['outerEnum'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "enum_string": obj.get("enum_string"), - "enum_string_required": obj.get("enum_string_required"), - "enum_integer_default": obj.get("enum_integer_default") if obj.get("enum_integer_default") is not None else 5, - "enum_integer": obj.get("enum_integer"), - "enum_number": obj.get("enum_number"), - "enum_string_single_member": obj.get("enum_string_single_member"), - "enum_integer_single_member": obj.get("enum_integer_single_member"), - "outerEnum": obj.get("outerEnum"), - "outerEnumInteger": obj.get("outerEnumInteger"), - "outerEnumDefaultValue": obj.get("outerEnumDefaultValue") if obj.get("outerEnumDefaultValue") is not None else OuterEnumDefaultValue.PLACED, - "outerEnumIntegerDefaultValue": obj.get("outerEnumIntegerDefaultValue") if obj.get("outerEnumIntegerDefaultValue") is not None else OuterEnumIntegerDefaultValue.NUMBER_0, - "enumNumberVendorExt": obj.get("enumNumberVendorExt"), - "enumStringVendorExt": obj.get("enumStringVendorExt") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/feeding.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/feeding.py index 5c406bc9e65e..3137d25e1585 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/feeding.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/feeding.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Feeding(BaseModel): """ Feeding """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning'] = Field( + ..., + description="task_name of the Feeding", + alias="task_name" + ) + function_name: Literal['care_nourish'] = Field( + ..., + description="function_name of the Feeding", + alias="function_name" + ) content: StrictStr additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -53,66 +62,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Feeding from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Feeding from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/file.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/file.py index 4c661cadabc4..c5b12aa2a78e 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/file.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/file.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class File(BaseModel): """ @@ -37,64 +38,27 @@ class File(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of File from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of File from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "sourceURI": obj.get("sourceURI") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/file_schema_test_class.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/file_schema_test_class.py index 09a543010f4d..127507d62b47 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/file_schema_test_class.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.file import File from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FileSchemaTestClass(BaseModel): """ @@ -39,75 +40,27 @@ class FileSchemaTestClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FileSchemaTestClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of file - if self.file: - _dict['file'] = self.file.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in files (list) - _items = [] - if self.files: - for _item_files in self.files: - if _item_files: - _items.append(_item_files.to_dict()) - _dict['files'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FileSchemaTestClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "file": File.from_dict(obj["file"]) if obj.get("file") is not None else None, - "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/first_ref.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/first_ref.py index 7680dfdf418c..e98d1438f4d9 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/first_ref.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/first_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FirstRef(BaseModel): """ @@ -38,69 +39,28 @@ class FirstRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FirstRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of self_ref - if self.self_ref: - _dict['self_ref'] = self.self_ref.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FirstRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "self_ref": SecondRef.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.second_ref import SecondRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/foo.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/foo.py index 81e3839ea17c..f29f366bb7d9 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/foo.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/foo.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Foo(BaseModel): """ @@ -37,64 +38,27 @@ class Foo(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Foo from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Foo from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar") if obj.get("bar") is not None else 'bar' - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/foo_get_default_response.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/foo_get_default_response.py index 4cd23db39125..63f2dc274345 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/foo_get_default_response.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/foo_get_default_response.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.foo import Foo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FooGetDefaultResponse(BaseModel): """ @@ -38,67 +39,27 @@ class FooGetDefaultResponse(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FooGetDefaultResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of string - if self.string: - _dict['string'] = self.string.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FooGetDefaultResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "string": Foo.from_dict(obj["string"]) if obj.get("string") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/format_test.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/format_test.py index 4aca97f91c48..8f7df0d352bc 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/format_test.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/format_test.py @@ -24,7 +24,8 @@ from typing_extensions import Annotated from uuid import UUID from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FormatTest(BaseModel): """ @@ -97,80 +98,27 @@ def pattern_with_digits_and_delimiter_validate_regular_expression(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FormatTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FormatTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "integer": obj.get("integer"), - "int32": obj.get("int32"), - "int64": obj.get("int64"), - "number": obj.get("number"), - "float": obj.get("float"), - "double": obj.get("double"), - "decimal": obj.get("decimal"), - "string": obj.get("string"), - "string_with_double_quote_pattern": obj.get("string_with_double_quote_pattern"), - "byte": obj.get("byte"), - "binary": obj.get("binary"), - "date": obj.get("date"), - "dateTime": obj.get("dateTime"), - "uuid": obj.get("uuid"), - "password": obj.get("password"), - "pattern_with_digits": obj.get("pattern_with_digits"), - "pattern_with_digits_and_delimiter": obj.get("pattern_with_digits_and_delimiter") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/has_only_read_only.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/has_only_read_only.py index 77360fedbae5..a8a2b326c9c8 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/has_only_read_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HasOnlyReadOnly(BaseModel): """ @@ -38,69 +39,27 @@ class HasOnlyReadOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HasOnlyReadOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * OpenAPI `readOnly` fields are excluded. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "bar", - "foo", - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HasOnlyReadOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar"), - "foo": obj.get("foo") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/health_check_result.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/health_check_result.py index 59f444aedaa3..675586246101 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/health_check_result.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/health_check_result.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HealthCheckResult(BaseModel): """ @@ -37,69 +38,27 @@ class HealthCheckResult(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HealthCheckResult from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if nullable_message (nullable) is None - # and model_fields_set contains the field - if self.nullable_message is None and "nullable_message" in self.model_fields_set: - _dict['NullableMessage'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HealthCheckResult from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "NullableMessage": obj.get("NullableMessage") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/hunting_dog.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/hunting_dog.py index f7d03f4044ea..b11e6efcc967 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/hunting_dog.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/hunting_dog.py @@ -22,7 +22,8 @@ from petstore_api.models.creature import Creature from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HuntingDog(Creature): """ @@ -39,69 +40,27 @@ class HuntingDog(Creature): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HuntingDog from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of info - if self.info: - _dict['info'] = self.info.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HuntingDog from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "info": CreatureInfo.from_dict(obj["info"]) if obj.get("info") is not None else None, - "type": obj.get("type"), - "isTrained": obj.get("isTrained") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/info.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/info.py index 94e663b3aaab..72dc4b91cc79 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/info.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/info.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.base_discriminator import BaseDiscriminator from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Info(BaseDiscriminator): """ @@ -38,68 +39,27 @@ class Info(BaseDiscriminator): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Info from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of val - if self.val: - _dict['val'] = self.val.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Info from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_typeName": obj.get("_typeName"), - "val": BaseDiscriminator.from_dict(obj["val"]) if obj.get("val") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/inner_dict_with_property.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/inner_dict_with_property.py index b43fa8b19fef..e03392c2d116 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/inner_dict_with_property.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/inner_dict_with_property.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class InnerDictWithProperty(BaseModel): """ @@ -37,64 +38,27 @@ class InnerDictWithProperty(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of InnerDictWithProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of InnerDictWithProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "aProperty": obj.get("aProperty") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/input_all_of.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/input_all_of.py index e4a81ff70006..661614b399a8 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/input_all_of.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/input_all_of.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class InputAllOf(BaseModel): """ @@ -38,76 +39,27 @@ class InputAllOf(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of InputAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in some_data (dict) - _field_dict = {} - if self.some_data: - for _key_some_data in self.some_data: - if self.some_data[_key_some_data]: - _field_dict[_key_some_data] = self.some_data[_key_some_data].to_dict() - _dict['some_data'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of InputAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "some_data": dict( - (_k, Tag.from_dict(_v)) - for _k, _v in obj["some_data"].items() - ) - if obj.get("some_data") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..c66bf1ab9772 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/int_or_string.py @@ -18,127 +18,55 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional from typing_extensions import Annotated -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] -class IntOrString(BaseModel): +class IntOrString(RootModel[Union[int, str]]): """ IntOrString """ - # data type: int - oneof_schema_1_validator: Optional[Annotated[int, Field(strict=True, ge=10)]] = None - # data type: str - oneof_schema_2_validator: Optional[StrictStr] = None - actual_instance: Optional[Union[int, str]] = None - one_of_schemas: Set[str] = { "int", "str" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[int, str] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = IntOrString.model_construct() - error_messages = [] - match = 0 - # validate data type: int - try: - instance.oneof_schema_1_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.oneof_schema_2_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into int - try: - # validation - instance.oneof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_1_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.oneof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_2_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/list_class.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/list_class.py index e00f3d820b88..4ea7c927440d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/list_class.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/list_class.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ListClass(BaseModel): """ @@ -37,64 +38,27 @@ class ListClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ListClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ListClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "123-list": obj.get("123-list") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/map_of_array_of_model.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/map_of_array_of_model.py index 68816ab29531..80a114e74c7a 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/map_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/map_of_array_of_model.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MapOfArrayOfModel(BaseModel): """ @@ -38,80 +39,27 @@ class MapOfArrayOfModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MapOfArrayOfModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in shop_id_to_org_online_lip_map (dict of array) - _field_dict_of_array = {} - if self.shop_id_to_org_online_lip_map: - for _key_shop_id_to_org_online_lip_map in self.shop_id_to_org_online_lip_map: - if self.shop_id_to_org_online_lip_map[_key_shop_id_to_org_online_lip_map] is not None: - _field_dict_of_array[_key_shop_id_to_org_online_lip_map] = [ - _item.to_dict() for _item in self.shop_id_to_org_online_lip_map[_key_shop_id_to_org_online_lip_map] - ] - _dict['shopIdToOrgOnlineLipMap'] = _field_dict_of_array - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MapOfArrayOfModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "shopIdToOrgOnlineLipMap": dict( - (_k, - [Tag.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("shopIdToOrgOnlineLipMap", {}).items() - ) - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/map_test.py index 4cefd36427f9..845b08e0a068 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/map_test.py @@ -20,14 +20,18 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MapTest(BaseModel): """ MapTest """ # noqa: E501 map_map_of_string: Optional[Dict[str, Dict[str, StrictStr]]] = None - map_of_enum_string: Optional[Dict[str, StrictStr]] = None + map_of_enum_string: Optional[Literal['UPPER', 'lower']] = Field( + None, + description="map_of_enum_string of the MapTest" + ) direct_map: Optional[Dict[str, StrictBool]] = None indirect_map: Optional[Dict[str, StrictBool]] = None additional_properties: Dict[str, Any] = {} @@ -51,67 +55,27 @@ def map_of_enum_string_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MapTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MapTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "map_map_of_string": obj.get("map_map_of_string"), - "map_of_enum_string": obj.get("map_of_enum_string"), - "direct_map": obj.get("direct_map"), - "indirect_map": obj.get("indirect_map") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/mixed_properties_and_additional_properties_class.py index c21f442bb798..a8d7a0b8161a 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -23,7 +23,8 @@ from uuid import UUID from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): """ @@ -42,78 +43,27 @@ class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in map (dict) - _field_dict = {} - if self.map: - for _key_map in self.map: - if self.map[_key_map]: - _field_dict[_key_map] = self.map[_key_map].to_dict() - _dict['map'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "uuid": obj.get("uuid"), - "dateTime": obj.get("dateTime"), - "map": dict( - (_k, Animal.from_dict(_v)) - for _k, _v in obj["map"].items() - ) - if obj.get("map") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model200_response.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model200_response.py index 60e43a0e28e6..aee3b7e0020d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model200_response.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model200_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Model200Response(BaseModel): """ @@ -38,65 +39,27 @@ class Model200Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Model200Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Model200Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name"), - "class": obj.get("class") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_api_response.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_api_response.py index 7141160c57d9..a750ecd6c9c9 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_api_response.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_api_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelApiResponse(BaseModel): """ @@ -39,66 +40,27 @@ class ModelApiResponse(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelApiResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelApiResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "code": obj.get("code"), - "type": obj.get("type"), - "message": obj.get("message") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_field.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_field.py index d7b03848fe16..b6af02e8f48d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_field.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_field.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelField(BaseModel): """ @@ -37,64 +38,27 @@ class ModelField(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelField from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelField from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "field": obj.get("field") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_return.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_return.py index 3f2558bc6e7d..6fc7eba6d7c3 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_return.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/model_return.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelReturn(BaseModel): """ @@ -37,64 +38,27 @@ class ModelReturn(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelReturn from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelReturn from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "return": obj.get("return") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/multi_arrays.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/multi_arrays.py index 80fa67f8a11c..55964857c0c3 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/multi_arrays.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/multi_arrays.py @@ -22,7 +22,8 @@ from petstore_api.models.file import File from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MultiArrays(BaseModel): """ @@ -40,79 +41,27 @@ class MultiArrays(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MultiArrays from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - # override the default output from pydantic by calling `to_dict()` of each item in files (list) - _items = [] - if self.files: - for _item_files in self.files: - if _item_files: - _items.append(_item_files.to_dict()) - _dict['files'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MultiArrays from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/name.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/name.py index 01b02f834137..9a9cc14ecb63 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/name.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/name.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Name(BaseModel): """ @@ -40,71 +41,27 @@ class Name(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Name from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * OpenAPI `readOnly` fields are excluded. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "snake_case", - "var_123_number", - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Name from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name"), - "snake_case": obj.get("snake_case"), - "property": obj.get("property"), - "123Number": obj.get("123Number") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nullable_class.py index cb27fbf691c2..e3244d22b190 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nullable_class.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictFloat, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NullableClass(BaseModel): """ @@ -50,131 +51,27 @@ class NullableClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NullableClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if required_integer_prop (nullable) is None - # and model_fields_set contains the field - if self.required_integer_prop is None and "required_integer_prop" in self.model_fields_set: - _dict['required_integer_prop'] = None - - # set to None if integer_prop (nullable) is None - # and model_fields_set contains the field - if self.integer_prop is None and "integer_prop" in self.model_fields_set: - _dict['integer_prop'] = None - - # set to None if number_prop (nullable) is None - # and model_fields_set contains the field - if self.number_prop is None and "number_prop" in self.model_fields_set: - _dict['number_prop'] = None - - # set to None if boolean_prop (nullable) is None - # and model_fields_set contains the field - if self.boolean_prop is None and "boolean_prop" in self.model_fields_set: - _dict['boolean_prop'] = None - - # set to None if string_prop (nullable) is None - # and model_fields_set contains the field - if self.string_prop is None and "string_prop" in self.model_fields_set: - _dict['string_prop'] = None - - # set to None if date_prop (nullable) is None - # and model_fields_set contains the field - if self.date_prop is None and "date_prop" in self.model_fields_set: - _dict['date_prop'] = None - - # set to None if datetime_prop (nullable) is None - # and model_fields_set contains the field - if self.datetime_prop is None and "datetime_prop" in self.model_fields_set: - _dict['datetime_prop'] = None - - # set to None if array_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.array_nullable_prop is None and "array_nullable_prop" in self.model_fields_set: - _dict['array_nullable_prop'] = None - - # set to None if array_and_items_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.array_and_items_nullable_prop is None and "array_and_items_nullable_prop" in self.model_fields_set: - _dict['array_and_items_nullable_prop'] = None - - # set to None if object_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.object_nullable_prop is None and "object_nullable_prop" in self.model_fields_set: - _dict['object_nullable_prop'] = None - - # set to None if object_and_items_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.object_and_items_nullable_prop is None and "object_and_items_nullable_prop" in self.model_fields_set: - _dict['object_and_items_nullable_prop'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NullableClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "required_integer_prop": obj.get("required_integer_prop"), - "integer_prop": obj.get("integer_prop"), - "number_prop": obj.get("number_prop"), - "boolean_prop": obj.get("boolean_prop"), - "string_prop": obj.get("string_prop"), - "date_prop": obj.get("date_prop"), - "datetime_prop": obj.get("datetime_prop"), - "array_nullable_prop": obj.get("array_nullable_prop"), - "array_and_items_nullable_prop": obj.get("array_and_items_nullable_prop"), - "array_items_nullable": obj.get("array_items_nullable"), - "object_nullable_prop": obj.get("object_nullable_prop"), - "object_and_items_nullable_prop": obj.get("object_and_items_nullable_prop"), - "object_items_nullable": obj.get("object_items_nullable") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nullable_property.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nullable_property.py index e73cd1509c90..9e529cbfd0e5 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nullable_property.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/nullable_property.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NullableProperty(BaseModel): """ @@ -49,70 +50,27 @@ def name_validate_regular_expression(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NullableProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if name (nullable) is None - # and model_fields_set contains the field - if self.name is None and "name" in self.model_fields_set: - _dict['name'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NullableProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/number_only.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/number_only.py index f74010e908bb..79b3e4c7dd1f 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/number_only.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictFloat from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NumberOnly(BaseModel): """ @@ -37,64 +38,27 @@ class NumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "JustNumber": obj.get("JustNumber") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/object_to_test_additional_properties.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/object_to_test_additional_properties.py index 097bdd34e2be..a3efd1d44032 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/object_to_test_additional_properties.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/object_to_test_additional_properties.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ObjectToTestAdditionalProperties(BaseModel): """ @@ -37,64 +38,27 @@ class ObjectToTestAdditionalProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ObjectToTestAdditionalProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ObjectToTestAdditionalProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "property": obj.get("property") if obj.get("property") is not None else False - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/object_with_deprecated_fields.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/object_with_deprecated_fields.py index 0c0cc840680b..2e952365e91e 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/object_with_deprecated_fields.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/object_with_deprecated_fields.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.deprecated_object import DeprecatedObject from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ObjectWithDeprecatedFields(BaseModel): """ @@ -41,70 +42,27 @@ class ObjectWithDeprecatedFields(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ObjectWithDeprecatedFields from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of deprecated_ref - if self.deprecated_ref: - _dict['deprecatedRef'] = self.deprecated_ref.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ObjectWithDeprecatedFields from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "uuid": obj.get("uuid"), - "id": obj.get("id"), - "deprecatedRef": DeprecatedObject.from_dict(obj["deprecatedRef"]) if obj.get("deprecatedRef") is not None else None, - "bars": obj.get("bars") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_enum_string.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_enum_string.py index f180178737db..bdbbebe0e1c4 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_enum_string.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/one_of_enum_string.py @@ -19,119 +19,55 @@ from typing import Any, List, Optional from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self ONEOFENUMSTRING_ONE_OF_SCHEMAS = ["EnumString1", "EnumString2"] -class OneOfEnumString(BaseModel): +class OneOfEnumString(RootModel[Union[EnumString1, EnumString2]]): """ oneOf enum strings """ - # data type: EnumString1 - oneof_schema_1_validator: Optional[EnumString1] = None - # data type: EnumString2 - oneof_schema_2_validator: Optional[EnumString2] = None - actual_instance: Optional[Union[EnumString1, EnumString2]] = None - one_of_schemas: Set[str] = { "EnumString1", "EnumString2" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[EnumString1, EnumString2] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = OneOfEnumString.model_construct() - error_messages = [] - match = 0 - # validate data type: EnumString1 - if not isinstance(v, EnumString1): - error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString1`") - else: - match += 1 - # validate data type: EnumString2 - if not isinstance(v, EnumString2): - error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString2`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into EnumString1 - try: - instance.actual_instance = EnumString1.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into EnumString2 - try: - instance.actual_instance = EnumString2.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], EnumString1, EnumString2]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/order.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/order.py index 12dd1ef117d2..3d94af52c8e3 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/order.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Order(BaseModel): """ @@ -31,7 +32,10 @@ class Order(BaseModel): pet_id: Optional[StrictInt] = Field(default=None, alias="petId") quantity: Optional[StrictInt] = None ship_date: Optional[datetime] = Field(default=None, alias="shipDate") - status: Optional[StrictStr] = Field(default=None, description="Order Status") + status: Optional[Literal['placed', 'approved', 'delivered']] = Field( + None, + description="Order Status" + ) complete: Optional[StrictBool] = False additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["id", "petId", "quantity", "shipDate", "status", "complete"] @@ -53,69 +57,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Order from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Order from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "petId": obj.get("petId"), - "quantity": obj.get("quantity"), - "shipDate": obj.get("shipDate"), - "status": obj.get("status"), - "complete": obj.get("complete") if obj.get("complete") is not None else False - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/outer_composite.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/outer_composite.py index 5242660b636b..49a79eb0a32f 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/outer_composite.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/outer_composite.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictFloat, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class OuterComposite(BaseModel): """ @@ -39,66 +40,27 @@ class OuterComposite(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of OuterComposite from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of OuterComposite from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "my_number": obj.get("my_number"), - "my_string": obj.get("my_string"), - "my_boolean": obj.get("my_boolean") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/outer_object_with_enum_property.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/outer_object_with_enum_property.py index f8d215a21c94..6de09c15996d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/outer_object_with_enum_property.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/outer_object_with_enum_property.py @@ -22,7 +22,8 @@ from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_integer import OuterEnumInteger from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class OuterObjectWithEnumProperty(BaseModel): """ @@ -40,70 +41,27 @@ class OuterObjectWithEnumProperty(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of OuterObjectWithEnumProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if str_value (nullable) is None - # and model_fields_set contains the field - if self.str_value is None and "str_value" in self.model_fields_set: - _dict['str_value'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of OuterObjectWithEnumProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "str_value": obj.get("str_value"), - "value": obj.get("value") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/parent.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/parent.py index 8a30758ab8fd..d9590e69f6dc 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/parent.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/parent.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Parent(BaseModel): """ @@ -38,76 +39,27 @@ class Parent(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Parent from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) - _field_dict = {} - if self.optional_dict: - for _key_optional_dict in self.optional_dict: - if self.optional_dict[_key_optional_dict]: - _field_dict[_key_optional_dict] = self.optional_dict[_key_optional_dict].to_dict() - _dict['optionalDict'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Parent from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "optionalDict": dict( - (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj["optionalDict"].items() - ) - if obj.get("optionalDict") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/parent_with_optional_dict.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/parent_with_optional_dict.py index 509693dd1441..87d0b13f8526 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/parent_with_optional_dict.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/parent_with_optional_dict.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ParentWithOptionalDict(BaseModel): """ @@ -38,76 +39,27 @@ class ParentWithOptionalDict(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ParentWithOptionalDict from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) - _field_dict = {} - if self.optional_dict: - for _key_optional_dict in self.optional_dict: - if self.optional_dict[_key_optional_dict]: - _field_dict[_key_optional_dict] = self.optional_dict[_key_optional_dict].to_dict() - _dict['optionalDict'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ParentWithOptionalDict from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "optionalDict": dict( - (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj["optionalDict"].items() - ) - if obj.get("optionalDict") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pet.py index 48f0c2fceeb7..d09bb6d73414 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pet.py @@ -23,7 +23,8 @@ from petstore_api.models.category import Category from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Pet(BaseModel): """ @@ -34,7 +35,10 @@ class Pet(BaseModel): name: StrictStr photo_urls: Annotated[List[StrictStr], Field(min_length=0)] = Field(alias="photoUrls") tags: Optional[List[Tag]] = None - status: Optional[StrictStr] = Field(default=None, description="pet status in the store") + status: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["id", "category", "name", "photoUrls", "tags", "status"] @@ -55,79 +59,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Pet from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of category - if self.category: - _dict['category'] = self.category.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Pet from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, - "name": obj.get("name"), - "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "status": obj.get("status") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pig.py index 06798245b8fe..6646e6d477cd 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pig.py @@ -19,137 +19,55 @@ from typing import Any, List, Optional from petstore_api.models.basque_pig import BasquePig from petstore_api.models.danish_pig import DanishPig -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] -class Pig(BaseModel): +class Pig(RootModel[Union[BasquePig, DanishPig]]): """ Pig """ - # data type: BasquePig - oneof_schema_1_validator: Optional[BasquePig] = None - # data type: DanishPig - oneof_schema_2_validator: Optional[DanishPig] = None - actual_instance: Optional[Union[BasquePig, DanishPig]] = None - one_of_schemas: Set[str] = { "BasquePig", "DanishPig" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[BasquePig, DanishPig] = Field( + ..., discriminator="class_name" ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - discriminator_value_class_map: Dict[str, str] = { - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = Pig.model_construct() - error_messages = [] - match = 0 - # validate data type: BasquePig - if not isinstance(v, BasquePig): - error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`") - else: - match += 1 - # validate data type: DanishPig - if not isinstance(v, DanishPig): - error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # use oneOf discriminator to lookup the data type - _data_type = json.loads(json_str).get("className") - if not _data_type: - raise ValueError("Failed to lookup data type from the field `className` in the input.") - - # check if data type is `BasquePig` - if _data_type == "BasquePig": - instance.actual_instance = BasquePig.from_json(json_str) - return instance - - # check if data type is `DanishPig` - if _data_type == "DanishPig": - instance.actual_instance = DanishPig.from_json(json_str) - return instance - - # deserialize data into BasquePig - try: - instance.actual_instance = BasquePig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DanishPig - try: - instance.actual_instance = DanishPig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pony_sizes.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pony_sizes.py index 74efce9a4d06..0de6140219e3 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pony_sizes.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/pony_sizes.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.type import Type from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PonySizes(BaseModel): """ @@ -38,64 +39,27 @@ class PonySizes(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PonySizes from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PonySizes from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "type": obj.get("type") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/poop_cleaning.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/poop_cleaning.py index 76eb72a941bf..b04faac7e90d 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/poop_cleaning.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/poop_cleaning.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PoopCleaning(BaseModel): """ PoopCleaning """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning'] = Field( + ..., + description="task_name of the PoopCleaning", + alias="task_name" + ) + function_name: Literal['care'] = Field( + ..., + description="function_name of the PoopCleaning", + alias="function_name" + ) content: StrictStr additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -53,66 +62,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PoopCleaning from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PoopCleaning from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/primitive_string.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/primitive_string.py index f7a971519f2f..6453538594f7 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/primitive_string.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/primitive_string.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.base_discriminator import BaseDiscriminator from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PrimitiveString(BaseDiscriminator): """ @@ -38,65 +39,27 @@ class PrimitiveString(BaseDiscriminator): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PrimitiveString from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PrimitiveString from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_typeName": obj.get("_typeName"), - "_value": obj.get("_value") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/property_map.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/property_map.py index 0da2a14293de..df57d2c77660 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/property_map.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/property_map.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PropertyMap(BaseModel): """ @@ -38,76 +39,27 @@ class PropertyMap(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PropertyMap from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in some_data (dict) - _field_dict = {} - if self.some_data: - for _key_some_data in self.some_data: - if self.some_data[_key_some_data]: - _field_dict[_key_some_data] = self.some_data[_key_some_data].to_dict() - _dict['some_data'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PropertyMap from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "some_data": dict( - (_k, Tag.from_dict(_v)) - for _k, _v in obj["some_data"].items() - ) - if obj.get("some_data") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/property_name_collision.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/property_name_collision.py index d07aef22cd82..2044934c0750 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/property_name_collision.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/property_name_collision.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PropertyNameCollision(BaseModel): """ @@ -39,66 +40,27 @@ class PropertyNameCollision(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PropertyNameCollision from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PropertyNameCollision from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_type": obj.get("_type"), - "type": obj.get("type"), - "type_": obj.get("type_") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/read_only_first.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/read_only_first.py index 5a4155fcfa13..c90ba68dd356 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/read_only_first.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/read_only_first.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ReadOnlyFirst(BaseModel): """ @@ -38,67 +39,27 @@ class ReadOnlyFirst(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ReadOnlyFirst from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "bar", - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ReadOnlyFirst from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar"), - "baz": obj.get("baz") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/second_circular_all_of_ref.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/second_circular_all_of_ref.py index 13d6327314c3..70d780804255 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/second_circular_all_of_ref.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/second_circular_all_of_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SecondCircularAllOfRef(BaseModel): """ @@ -38,73 +39,28 @@ class SecondCircularAllOfRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SecondCircularAllOfRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in circular_all_of_ref (list) - _items = [] - if self.circular_all_of_ref: - for _item_circular_all_of_ref in self.circular_all_of_ref: - if _item_circular_all_of_ref: - _items.append(_item_circular_all_of_ref.to_dict()) - _dict['circularAllOfRef'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SecondCircularAllOfRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name"), - "circularAllOfRef": [CircularAllOfRef.from_dict(_item) for _item in obj["circularAllOfRef"]] if obj.get("circularAllOfRef") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.circular_all_of_ref import CircularAllOfRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/second_ref.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/second_ref.py index 701e0dccaacf..79c38f4ea4ae 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/second_ref.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/second_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SecondRef(BaseModel): """ @@ -38,69 +39,28 @@ class SecondRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SecondRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of circular_ref - if self.circular_ref: - _dict['circular_ref'] = self.circular_ref.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SecondRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "circular_ref": CircularReferenceModel.from_dict(obj["circular_ref"]) if obj.get("circular_ref") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.circular_reference_model import CircularReferenceModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/self_reference_model.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/self_reference_model.py index 0273b10dada6..0b2dea762dcc 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/self_reference_model.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/self_reference_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SelfReferenceModel(BaseModel): """ @@ -38,69 +39,28 @@ class SelfReferenceModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SelfReferenceModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested - if self.nested: - _dict['nested'] = self.nested.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SelfReferenceModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested": DummyModel.from_dict(obj["nested"]) if obj.get("nested") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.dummy_model import DummyModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/special_model_name.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/special_model_name.py index 84686054875a..8eabe68b9eb3 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/special_model_name.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/special_model_name.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SpecialModelName(BaseModel): """ @@ -37,64 +38,27 @@ class SpecialModelName(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SpecialModelName from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SpecialModelName from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "$special[property.name]": obj.get("$special[property.name]") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/special_name.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/special_name.py index e43761d33dfc..52aa54ac7019 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/special_name.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/special_name.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.category import Category from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SpecialName(BaseModel): """ @@ -29,7 +30,10 @@ class SpecialName(BaseModel): """ # noqa: E501 var_property: Optional[StrictInt] = Field(default=None, alias="property") var_async: Optional[Category] = Field(default=None, alias="async") - var_schema: Optional[StrictStr] = Field(default=None, description="pet status in the store", alias="schema") + var_schema: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["property", "async", "schema"] @@ -50,69 +54,27 @@ def var_schema_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SpecialName from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of var_async - if self.var_async: - _dict['async'] = self.var_async.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SpecialName from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "property": obj.get("property"), - "async": Category.from_dict(obj["async"]) if obj.get("async") is not None else None, - "schema": obj.get("schema") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tag.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tag.py index b3893aecb683..5b8ee944ee7b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tag.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tag.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tag(BaseModel): """ @@ -38,65 +39,27 @@ class Tag(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tag from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tag from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task.py index a8e0fa11ff84..c37aafc8762a 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task.py @@ -22,7 +22,8 @@ from uuid import UUID from petstore_api.models.task_activity import TaskActivity from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Task(BaseModel): """ @@ -40,68 +41,27 @@ class Task(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Task from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of activity - if self.activity: - _dict['activity'] = self.activity.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Task from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "activity": TaskActivity.from_dict(obj["activity"]) if obj.get("activity") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task_activity.py index cc1e1fc5a60f..39a1c0bbc375 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/task_activity.py @@ -20,132 +20,55 @@ from petstore_api.models.bathing import Bathing from petstore_api.models.feeding import Feeding from petstore_api.models.poop_cleaning import PoopCleaning -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] -class TaskActivity(BaseModel): +class TaskActivity(RootModel[Union[Bathing, Feeding, PoopCleaning]]): """ TaskActivity """ - # data type: PoopCleaning - oneof_schema_1_validator: Optional[PoopCleaning] = None - # data type: Feeding - oneof_schema_2_validator: Optional[Feeding] = None - # data type: Bathing - oneof_schema_3_validator: Optional[Bathing] = None - actual_instance: Optional[Union[Bathing, Feeding, PoopCleaning]] = None - one_of_schemas: Set[str] = { "Bathing", "Feeding", "PoopCleaning" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[Bathing, Feeding, PoopCleaning] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = TaskActivity.model_construct() - error_messages = [] - match = 0 - # validate data type: PoopCleaning - if not isinstance(v, PoopCleaning): - error_messages.append(f"Error! Input type `{type(v)}` is not `PoopCleaning`") - else: - match += 1 - # validate data type: Feeding - if not isinstance(v, Feeding): - error_messages.append(f"Error! Input type `{type(v)}` is not `Feeding`") - else: - match += 1 - # validate data type: Bathing - if not isinstance(v, Bathing): - error_messages.append(f"Error! Input type `{type(v)}` is not `Bathing`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into PoopCleaning - try: - instance.actual_instance = PoopCleaning.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into Feeding - try: - instance.actual_instance = Feeding.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into Bathing - try: - instance.actual_instance = Bathing.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_error_responses_with_model400_response.py index f5fe068c9111..cc234881eb3b 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_error_responses_with_model400_response.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_error_responses_with_model400_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestErrorResponsesWithModel400Response(BaseModel): """ @@ -37,64 +38,27 @@ class TestErrorResponsesWithModel400Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel400Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel400Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "reason400": obj.get("reason400") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_error_responses_with_model404_response.py index 39e6c512ed3e..5cefd03da6cf 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_error_responses_with_model404_response.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_error_responses_with_model404_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestErrorResponsesWithModel404Response(BaseModel): """ @@ -37,64 +38,27 @@ class TestErrorResponsesWithModel404Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel404Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel404Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "reason404": obj.get("reason404") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_inline_freeform_additional_properties_request.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_inline_freeform_additional_properties_request.py index 7b93d84864f2..83309fd58987 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_inline_freeform_additional_properties_request.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_inline_freeform_additional_properties_request.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): """ @@ -37,64 +38,27 @@ class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "someProperty": obj.get("someProperty") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_model_with_enum_default.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_model_with_enum_default.py index 4bff5e699a37..103ee7667394 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_model_with_enum_default.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_model_with_enum_default.py @@ -22,7 +22,8 @@ from petstore_api.models.test_enum import TestEnum from petstore_api.models.test_enum_with_default import TestEnumWithDefault from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestModelWithEnumDefault(BaseModel): """ @@ -32,7 +33,10 @@ class TestModelWithEnumDefault(BaseModel): test_string: Optional[StrictStr] = None test_enum_with_default: Optional[TestEnumWithDefault] = TestEnumWithDefault.ZWEI test_string_with_default: Optional[StrictStr] = 'ahoy matey' - test_inline_defined_enum_with_default: Optional[StrictStr] = 'B' + test_inline_defined_enum_with_default: Optional[Literal['A', 'B', 'C']] = Field( + None, + description="test_inline_defined_enum_with_default of the TestModelWithEnumDefault" + ) additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["test_enum", "test_string", "test_enum_with_default", "test_string_with_default", "test_inline_defined_enum_with_default"] @@ -53,68 +57,27 @@ def test_inline_defined_enum_with_default_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestModelWithEnumDefault from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestModelWithEnumDefault from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "test_enum": obj.get("test_enum"), - "test_string": obj.get("test_string"), - "test_enum_with_default": obj.get("test_enum_with_default") if obj.get("test_enum_with_default") is not None else TestEnumWithDefault.ZWEI, - "test_string_with_default": obj.get("test_string_with_default") if obj.get("test_string_with_default") is not None else 'ahoy matey', - "test_inline_defined_enum_with_default": obj.get("test_inline_defined_enum_with_default") if obj.get("test_inline_defined_enum_with_default") is not None else 'B' - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_object_for_multipart_requests_request_marker.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_object_for_multipart_requests_request_marker.py index c31d72482d59..cfd79254cbe9 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_object_for_multipart_requests_request_marker.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/test_object_for_multipart_requests_request_marker.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestObjectForMultipartRequestsRequestMarker(BaseModel): """ @@ -37,64 +38,27 @@ class TestObjectForMultipartRequestsRequestMarker(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestObjectForMultipartRequestsRequestMarker from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestObjectForMultipartRequestsRequestMarker from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tiger.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tiger.py index c2dab004fe1a..7d2c375e47e0 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tiger.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/tiger.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tiger(BaseModel): """ @@ -37,64 +38,27 @@ class Tiger(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tiger from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tiger from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "skill": obj.get("skill") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py index e5b5cb4ddeda..3717b3d245bc 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UnnamedDictWithAdditionalModelListProperties(BaseModel): """ @@ -38,80 +39,27 @@ class UnnamedDictWithAdditionalModelListProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in dict_property (dict of array) - _field_dict_of_array = {} - if self.dict_property: - for _key_dict_property in self.dict_property: - if self.dict_property[_key_dict_property] is not None: - _field_dict_of_array[_key_dict_property] = [ - _item.to_dict() for _item in self.dict_property[_key_dict_property] - ] - _dict['dictProperty'] = _field_dict_of_array - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalModelListProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "dictProperty": dict( - (_k, - [CreatureInfo.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("dictProperty", {}).items() - ) - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py index f4c7625325c8..90cbb19b8e9e 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UnnamedDictWithAdditionalStringListProperties(BaseModel): """ @@ -37,64 +38,27 @@ class UnnamedDictWithAdditionalStringListProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalStringListProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "dictProperty": obj.get("dictProperty") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/upload_file_with_additional_properties_request_object.py index 6d79131bfe79..0a689487b4c5 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/upload_file_with_additional_properties_request_object.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): """ @@ -37,64 +38,27 @@ class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/user.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/user.py index ceeb6d4ae54c..3e775dd2e752 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/user.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/user.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class User(BaseModel): """ @@ -44,71 +45,27 @@ class User(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of User from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of User from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "username": obj.get("username"), - "firstName": obj.get("firstName"), - "lastName": obj.get("lastName"), - "email": obj.get("email"), - "password": obj.get("password"), - "phone": obj.get("phone"), - "userStatus": obj.get("userStatus") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/with_nested_one_of.py b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/with_nested_one_of.py index eb7e90879e90..c088f14d6330 100644 --- a/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/with_nested_one_of.py +++ b/samples/openapi3/client/petstore/python-lazyImports/petstore_api/models/with_nested_one_of.py @@ -22,7 +22,8 @@ from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.pig import Pig from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class WithNestedOneOf(BaseModel): """ @@ -41,72 +42,27 @@ class WithNestedOneOf(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of WithNestedOneOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested_pig - if self.nested_pig: - _dict['nested_pig'] = self.nested_pig.to_dict() - # override the default output from pydantic by calling `to_dict()` of nested_oneof_enum_string - if self.nested_oneof_enum_string: - _dict['nested_oneof_enum_string'] = self.nested_oneof_enum_string.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of WithNestedOneOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested_pig": Pig.from_dict(obj["nested_pig"]) if obj.get("nested_pig") is not None else None, - "nested_oneof_enum_string": OneOfEnumString.from_dict(obj["nested_oneof_enum_string"]) if obj.get("nested_oneof_enum_string") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md index 314cba3a614c..b94c1e6d7d19 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_any_type import AdditionalPropert # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesAnyType from a JSON string -additional_properties_any_type_instance = AdditionalPropertiesAnyType.from_json(json) +additional_properties_any_type_instance = AdditionalPropertiesAnyType.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesAnyType.to_json()) +print(additional_properties_any_type_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_any_type_dict = additional_properties_any_type_instance.to_dict() +additional_properties_any_type_dict = additional_properties_any_type_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesAnyType from a dict -additional_properties_any_type_from_dict = AdditionalPropertiesAnyType.from_dict(additional_properties_any_type_dict) +additional_properties_any_type_from_dict = AdditionalPropertiesAnyType.model_validate(additional_properties_any_type_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md index 8d4c08707f55..4c880d6853e8 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md @@ -16,14 +16,14 @@ from petstore_api.models.additional_properties_class import AdditionalProperties # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesClass from a JSON string -additional_properties_class_instance = AdditionalPropertiesClass.from_json(json) +additional_properties_class_instance = AdditionalPropertiesClass.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesClass.to_json()) +print(additional_properties_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_class_dict = additional_properties_class_instance.to_dict() +additional_properties_class_dict = additional_properties_class_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesClass from a dict -additional_properties_class_from_dict = AdditionalPropertiesClass.from_dict(additional_properties_class_dict) +additional_properties_class_from_dict = AdditionalPropertiesClass.model_validate(additional_properties_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md index d647ec64896f..bf6743709338 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_object import AdditionalPropertie # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesObject from a JSON string -additional_properties_object_instance = AdditionalPropertiesObject.from_json(json) +additional_properties_object_instance = AdditionalPropertiesObject.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesObject.to_json()) +print(additional_properties_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_object_dict = additional_properties_object_instance.to_dict() +additional_properties_object_dict = additional_properties_object_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesObject from a dict -additional_properties_object_from_dict = AdditionalPropertiesObject.from_dict(additional_properties_object_dict) +additional_properties_object_from_dict = AdditionalPropertiesObject.model_validate(additional_properties_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md index 061f5524872b..1cb2a02f7584 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.additional_properties_with_description_only import Addi # TODO update the JSON string below json = "{}" # create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string -additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.from_json(json) +additional_properties_with_description_only_instance = AdditionalPropertiesWithDescriptionOnly.model_validate_json(json) # print the JSON string representation of the object -print(AdditionalPropertiesWithDescriptionOnly.to_json()) +print(additional_properties_with_description_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.to_dict() +additional_properties_with_description_only_dict = additional_properties_with_description_only_instance.model_dump(by_alias=True) # create an instance of AdditionalPropertiesWithDescriptionOnly from a dict -additional_properties_with_description_only_from_dict = AdditionalPropertiesWithDescriptionOnly.from_dict(additional_properties_with_description_only_dict) +additional_properties_with_description_only_from_dict = AdditionalPropertiesWithDescriptionOnly.model_validate(additional_properties_with_description_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/AllOfSuperModel.md b/samples/openapi3/client/petstore/python/docs/AllOfSuperModel.md index 421a1527f1ef..88cb95097517 100644 --- a/samples/openapi3/client/petstore/python/docs/AllOfSuperModel.md +++ b/samples/openapi3/client/petstore/python/docs/AllOfSuperModel.md @@ -15,14 +15,14 @@ from petstore_api.models.all_of_super_model import AllOfSuperModel # TODO update the JSON string below json = "{}" # create an instance of AllOfSuperModel from a JSON string -all_of_super_model_instance = AllOfSuperModel.from_json(json) +all_of_super_model_instance = AllOfSuperModel.model_validate_json(json) # print the JSON string representation of the object -print(AllOfSuperModel.to_json()) +print(all_of_super_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -all_of_super_model_dict = all_of_super_model_instance.to_dict() +all_of_super_model_dict = all_of_super_model_instance.model_dump(by_alias=True) # create an instance of AllOfSuperModel from a dict -all_of_super_model_from_dict = AllOfSuperModel.from_dict(all_of_super_model_dict) +all_of_super_model_from_dict = AllOfSuperModel.model_validate(all_of_super_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/AllOfWithSingleRef.md b/samples/openapi3/client/petstore/python/docs/AllOfWithSingleRef.md index 203a4b5da3d5..dd0f755dfe65 100644 --- a/samples/openapi3/client/petstore/python/docs/AllOfWithSingleRef.md +++ b/samples/openapi3/client/petstore/python/docs/AllOfWithSingleRef.md @@ -16,14 +16,14 @@ from petstore_api.models.all_of_with_single_ref import AllOfWithSingleRef # TODO update the JSON string below json = "{}" # create an instance of AllOfWithSingleRef from a JSON string -all_of_with_single_ref_instance = AllOfWithSingleRef.from_json(json) +all_of_with_single_ref_instance = AllOfWithSingleRef.model_validate_json(json) # print the JSON string representation of the object -print(AllOfWithSingleRef.to_json()) +print(all_of_with_single_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -all_of_with_single_ref_dict = all_of_with_single_ref_instance.to_dict() +all_of_with_single_ref_dict = all_of_with_single_ref_instance.model_dump(by_alias=True) # create an instance of AllOfWithSingleRef from a dict -all_of_with_single_ref_from_dict = AllOfWithSingleRef.from_dict(all_of_with_single_ref_dict) +all_of_with_single_ref_from_dict = AllOfWithSingleRef.model_validate(all_of_with_single_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Animal.md b/samples/openapi3/client/petstore/python/docs/Animal.md index 381d27b66e44..fcded75f52be 100644 --- a/samples/openapi3/client/petstore/python/docs/Animal.md +++ b/samples/openapi3/client/petstore/python/docs/Animal.md @@ -16,14 +16,14 @@ from petstore_api.models.animal import Animal # TODO update the JSON string below json = "{}" # create an instance of Animal from a JSON string -animal_instance = Animal.from_json(json) +animal_instance = Animal.model_validate_json(json) # print the JSON string representation of the object -print(Animal.to_json()) +print(animal_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -animal_dict = animal_instance.to_dict() +animal_dict = animal_instance.model_dump(by_alias=True) # create an instance of Animal from a dict -animal_from_dict = Animal.from_dict(animal_dict) +animal_from_dict = Animal.model_validate(animal_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/AnyOfColor.md b/samples/openapi3/client/petstore/python/docs/AnyOfColor.md index 6ed75dd7b48a..02aab883b2b0 100644 --- a/samples/openapi3/client/petstore/python/docs/AnyOfColor.md +++ b/samples/openapi3/client/petstore/python/docs/AnyOfColor.md @@ -15,14 +15,14 @@ from petstore_api.models.any_of_color import AnyOfColor # TODO update the JSON string below json = "{}" # create an instance of AnyOfColor from a JSON string -any_of_color_instance = AnyOfColor.from_json(json) +any_of_color_instance = AnyOfColor.model_validate_json(json) # print the JSON string representation of the object -print(AnyOfColor.to_json()) +print(any_of_color_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -any_of_color_dict = any_of_color_instance.to_dict() +any_of_color_dict = any_of_color_instance.model_dump(by_alias=True) # create an instance of AnyOfColor from a dict -any_of_color_from_dict = AnyOfColor.from_dict(any_of_color_dict) +any_of_color_from_dict = AnyOfColor.model_validate(any_of_color_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/AnyOfPig.md b/samples/openapi3/client/petstore/python/docs/AnyOfPig.md index 9367e2261898..db2878121f29 100644 --- a/samples/openapi3/client/petstore/python/docs/AnyOfPig.md +++ b/samples/openapi3/client/petstore/python/docs/AnyOfPig.md @@ -17,14 +17,14 @@ from petstore_api.models.any_of_pig import AnyOfPig # TODO update the JSON string below json = "{}" # create an instance of AnyOfPig from a JSON string -any_of_pig_instance = AnyOfPig.from_json(json) +any_of_pig_instance = AnyOfPig.model_validate_json(json) # print the JSON string representation of the object -print(AnyOfPig.to_json()) +print(any_of_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -any_of_pig_dict = any_of_pig_instance.to_dict() +any_of_pig_dict = any_of_pig_instance.model_dump(by_alias=True) # create an instance of AnyOfPig from a dict -any_of_pig_from_dict = AnyOfPig.from_dict(any_of_pig_dict) +any_of_pig_from_dict = AnyOfPig.model_validate(any_of_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfModel.md b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfModel.md index f866863d53f9..e8274d8fbb52 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfModel.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel # TODO update the JSON string below json = "{}" # create an instance of ArrayOfArrayOfModel from a JSON string -array_of_array_of_model_instance = ArrayOfArrayOfModel.from_json(json) +array_of_array_of_model_instance = ArrayOfArrayOfModel.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfArrayOfModel.to_json()) +print(array_of_array_of_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_array_of_model_dict = array_of_array_of_model_instance.to_dict() +array_of_array_of_model_dict = array_of_array_of_model_instance.model_dump(by_alias=True) # create an instance of ArrayOfArrayOfModel from a dict -array_of_array_of_model_from_dict = ArrayOfArrayOfModel.from_dict(array_of_array_of_model_dict) +array_of_array_of_model_from_dict = ArrayOfArrayOfModel.model_validate(array_of_array_of_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md index 32bd2dfbf1e2..8931a1c7e467 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumb # TODO update the JSON string below json = "{}" # create an instance of ArrayOfArrayOfNumberOnly from a JSON string -array_of_array_of_number_only_instance = ArrayOfArrayOfNumberOnly.from_json(json) +array_of_array_of_number_only_instance = ArrayOfArrayOfNumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfArrayOfNumberOnly.to_json()) +print(array_of_array_of_number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_array_of_number_only_dict = array_of_array_of_number_only_instance.to_dict() +array_of_array_of_number_only_dict = array_of_array_of_number_only_instance.model_dump(by_alias=True) # create an instance of ArrayOfArrayOfNumberOnly from a dict -array_of_array_of_number_only_from_dict = ArrayOfArrayOfNumberOnly.from_dict(array_of_array_of_number_only_dict) +array_of_array_of_number_only_from_dict = ArrayOfArrayOfNumberOnly.model_validate(array_of_array_of_number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md index b814d7594942..a709583be699 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.array_of_number_only import ArrayOfNumberOnly # TODO update the JSON string below json = "{}" # create an instance of ArrayOfNumberOnly from a JSON string -array_of_number_only_instance = ArrayOfNumberOnly.from_json(json) +array_of_number_only_instance = ArrayOfNumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(ArrayOfNumberOnly.to_json()) +print(array_of_number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_of_number_only_dict = array_of_number_only_instance.to_dict() +array_of_number_only_dict = array_of_number_only_instance.model_dump(by_alias=True) # create an instance of ArrayOfNumberOnly from a dict -array_of_number_only_from_dict = ArrayOfNumberOnly.from_dict(array_of_number_only_dict) +array_of_number_only_from_dict = ArrayOfNumberOnly.model_validate(array_of_number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ArrayTest.md b/samples/openapi3/client/petstore/python/docs/ArrayTest.md index ed871fae662d..a99eb056c5ca 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayTest.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayTest.md @@ -18,14 +18,14 @@ from petstore_api.models.array_test import ArrayTest # TODO update the JSON string below json = "{}" # create an instance of ArrayTest from a JSON string -array_test_instance = ArrayTest.from_json(json) +array_test_instance = ArrayTest.model_validate_json(json) # print the JSON string representation of the object -print(ArrayTest.to_json()) +print(array_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -array_test_dict = array_test_instance.to_dict() +array_test_dict = array_test_instance.model_dump(by_alias=True) # create an instance of ArrayTest from a dict -array_test_from_dict = ArrayTest.from_dict(array_test_dict) +array_test_from_dict = ArrayTest.model_validate(array_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/BaseDiscriminator.md b/samples/openapi3/client/petstore/python/docs/BaseDiscriminator.md index fcdbeb032e68..0482396cbcf8 100644 --- a/samples/openapi3/client/petstore/python/docs/BaseDiscriminator.md +++ b/samples/openapi3/client/petstore/python/docs/BaseDiscriminator.md @@ -15,14 +15,14 @@ from petstore_api.models.base_discriminator import BaseDiscriminator # TODO update the JSON string below json = "{}" # create an instance of BaseDiscriminator from a JSON string -base_discriminator_instance = BaseDiscriminator.from_json(json) +base_discriminator_instance = BaseDiscriminator.model_validate_json(json) # print the JSON string representation of the object -print(BaseDiscriminator.to_json()) +print(base_discriminator_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -base_discriminator_dict = base_discriminator_instance.to_dict() +base_discriminator_dict = base_discriminator_instance.model_dump(by_alias=True) # create an instance of BaseDiscriminator from a dict -base_discriminator_from_dict = BaseDiscriminator.from_dict(base_discriminator_dict) +base_discriminator_from_dict = BaseDiscriminator.model_validate(base_discriminator_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/BasquePig.md b/samples/openapi3/client/petstore/python/docs/BasquePig.md index ee28d628722f..9844d05b3740 100644 --- a/samples/openapi3/client/petstore/python/docs/BasquePig.md +++ b/samples/openapi3/client/petstore/python/docs/BasquePig.md @@ -16,14 +16,14 @@ from petstore_api.models.basque_pig import BasquePig # TODO update the JSON string below json = "{}" # create an instance of BasquePig from a JSON string -basque_pig_instance = BasquePig.from_json(json) +basque_pig_instance = BasquePig.model_validate_json(json) # print the JSON string representation of the object -print(BasquePig.to_json()) +print(basque_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -basque_pig_dict = basque_pig_instance.to_dict() +basque_pig_dict = basque_pig_instance.model_dump(by_alias=True) # create an instance of BasquePig from a dict -basque_pig_from_dict = BasquePig.from_dict(basque_pig_dict) +basque_pig_from_dict = BasquePig.model_validate(basque_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Bathing.md b/samples/openapi3/client/petstore/python/docs/Bathing.md index 6ad70e2f67cc..2c8d8332629b 100644 --- a/samples/openapi3/client/petstore/python/docs/Bathing.md +++ b/samples/openapi3/client/petstore/python/docs/Bathing.md @@ -17,14 +17,14 @@ from petstore_api.models.bathing import Bathing # TODO update the JSON string below json = "{}" # create an instance of Bathing from a JSON string -bathing_instance = Bathing.from_json(json) +bathing_instance = Bathing.model_validate_json(json) # print the JSON string representation of the object -print(Bathing.to_json()) +print(bathing_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -bathing_dict = bathing_instance.to_dict() +bathing_dict = bathing_instance.model_dump(by_alias=True) # create an instance of Bathing from a dict -bathing_from_dict = Bathing.from_dict(bathing_dict) +bathing_from_dict = Bathing.model_validate(bathing_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Capitalization.md b/samples/openapi3/client/petstore/python/docs/Capitalization.md index 6f564a8ed8c9..55fcc0c01cb2 100644 --- a/samples/openapi3/client/petstore/python/docs/Capitalization.md +++ b/samples/openapi3/client/petstore/python/docs/Capitalization.md @@ -20,14 +20,14 @@ from petstore_api.models.capitalization import Capitalization # TODO update the JSON string below json = "{}" # create an instance of Capitalization from a JSON string -capitalization_instance = Capitalization.from_json(json) +capitalization_instance = Capitalization.model_validate_json(json) # print the JSON string representation of the object -print(Capitalization.to_json()) +print(capitalization_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -capitalization_dict = capitalization_instance.to_dict() +capitalization_dict = capitalization_instance.model_dump(by_alias=True) # create an instance of Capitalization from a dict -capitalization_from_dict = Capitalization.from_dict(capitalization_dict) +capitalization_from_dict = Capitalization.model_validate(capitalization_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Cat.md b/samples/openapi3/client/petstore/python/docs/Cat.md index d0e39efdb33e..0845d68bd487 100644 --- a/samples/openapi3/client/petstore/python/docs/Cat.md +++ b/samples/openapi3/client/petstore/python/docs/Cat.md @@ -15,14 +15,14 @@ from petstore_api.models.cat import Cat # TODO update the JSON string below json = "{}" # create an instance of Cat from a JSON string -cat_instance = Cat.from_json(json) +cat_instance = Cat.model_validate_json(json) # print the JSON string representation of the object -print(Cat.to_json()) +print(cat_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -cat_dict = cat_instance.to_dict() +cat_dict = cat_instance.model_dump(by_alias=True) # create an instance of Cat from a dict -cat_from_dict = Cat.from_dict(cat_dict) +cat_from_dict = Cat.model_validate(cat_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Category.md b/samples/openapi3/client/petstore/python/docs/Category.md index dbde14b7344c..8a14791c7925 100644 --- a/samples/openapi3/client/petstore/python/docs/Category.md +++ b/samples/openapi3/client/petstore/python/docs/Category.md @@ -16,14 +16,14 @@ from petstore_api.models.category import Category # TODO update the JSON string below json = "{}" # create an instance of Category from a JSON string -category_instance = Category.from_json(json) +category_instance = Category.model_validate_json(json) # print the JSON string representation of the object -print(Category.to_json()) +print(category_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -category_dict = category_instance.to_dict() +category_dict = category_instance.model_dump(by_alias=True) # create an instance of Category from a dict -category_from_dict = Category.from_dict(category_dict) +category_from_dict = Category.model_validate(category_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/CircularAllOfRef.md b/samples/openapi3/client/petstore/python/docs/CircularAllOfRef.md index 65b171177e58..f937a53cfe3c 100644 --- a/samples/openapi3/client/petstore/python/docs/CircularAllOfRef.md +++ b/samples/openapi3/client/petstore/python/docs/CircularAllOfRef.md @@ -16,14 +16,14 @@ from petstore_api.models.circular_all_of_ref import CircularAllOfRef # TODO update the JSON string below json = "{}" # create an instance of CircularAllOfRef from a JSON string -circular_all_of_ref_instance = CircularAllOfRef.from_json(json) +circular_all_of_ref_instance = CircularAllOfRef.model_validate_json(json) # print the JSON string representation of the object -print(CircularAllOfRef.to_json()) +print(circular_all_of_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -circular_all_of_ref_dict = circular_all_of_ref_instance.to_dict() +circular_all_of_ref_dict = circular_all_of_ref_instance.model_dump(by_alias=True) # create an instance of CircularAllOfRef from a dict -circular_all_of_ref_from_dict = CircularAllOfRef.from_dict(circular_all_of_ref_dict) +circular_all_of_ref_from_dict = CircularAllOfRef.model_validate(circular_all_of_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/CircularReferenceModel.md b/samples/openapi3/client/petstore/python/docs/CircularReferenceModel.md index 87216f7273ab..9a39f46e5d7d 100644 --- a/samples/openapi3/client/petstore/python/docs/CircularReferenceModel.md +++ b/samples/openapi3/client/petstore/python/docs/CircularReferenceModel.md @@ -16,14 +16,14 @@ from petstore_api.models.circular_reference_model import CircularReferenceModel # TODO update the JSON string below json = "{}" # create an instance of CircularReferenceModel from a JSON string -circular_reference_model_instance = CircularReferenceModel.from_json(json) +circular_reference_model_instance = CircularReferenceModel.model_validate_json(json) # print the JSON string representation of the object -print(CircularReferenceModel.to_json()) +print(circular_reference_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -circular_reference_model_dict = circular_reference_model_instance.to_dict() +circular_reference_model_dict = circular_reference_model_instance.model_dump(by_alias=True) # create an instance of CircularReferenceModel from a dict -circular_reference_model_from_dict = CircularReferenceModel.from_dict(circular_reference_model_dict) +circular_reference_model_from_dict = CircularReferenceModel.model_validate(circular_reference_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ClassModel.md b/samples/openapi3/client/petstore/python/docs/ClassModel.md index ea76a5c157bf..50fbfefa7661 100644 --- a/samples/openapi3/client/petstore/python/docs/ClassModel.md +++ b/samples/openapi3/client/petstore/python/docs/ClassModel.md @@ -16,14 +16,14 @@ from petstore_api.models.class_model import ClassModel # TODO update the JSON string below json = "{}" # create an instance of ClassModel from a JSON string -class_model_instance = ClassModel.from_json(json) +class_model_instance = ClassModel.model_validate_json(json) # print the JSON string representation of the object -print(ClassModel.to_json()) +print(class_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -class_model_dict = class_model_instance.to_dict() +class_model_dict = class_model_instance.model_dump(by_alias=True) # create an instance of ClassModel from a dict -class_model_from_dict = ClassModel.from_dict(class_model_dict) +class_model_from_dict = ClassModel.model_validate(class_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Client.md b/samples/openapi3/client/petstore/python/docs/Client.md index 22321c189150..160a80da457f 100644 --- a/samples/openapi3/client/petstore/python/docs/Client.md +++ b/samples/openapi3/client/petstore/python/docs/Client.md @@ -15,14 +15,14 @@ from petstore_api.models.client import Client # TODO update the JSON string below json = "{}" # create an instance of Client from a JSON string -client_instance = Client.from_json(json) +client_instance = Client.model_validate_json(json) # print the JSON string representation of the object -print(Client.to_json()) +print(client_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -client_dict = client_instance.to_dict() +client_dict = client_instance.model_dump(by_alias=True) # create an instance of Client from a dict -client_from_dict = Client.from_dict(client_dict) +client_from_dict = Client.model_validate(client_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Color.md b/samples/openapi3/client/petstore/python/docs/Color.md index 9ac3ab2e91f4..1425ff185040 100644 --- a/samples/openapi3/client/petstore/python/docs/Color.md +++ b/samples/openapi3/client/petstore/python/docs/Color.md @@ -15,14 +15,14 @@ from petstore_api.models.color import Color # TODO update the JSON string below json = "{}" # create an instance of Color from a JSON string -color_instance = Color.from_json(json) +color_instance = Color.model_validate_json(json) # print the JSON string representation of the object -print(Color.to_json()) +print(color_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -color_dict = color_instance.to_dict() +color_dict = color_instance.model_dump(by_alias=True) # create an instance of Color from a dict -color_from_dict = Color.from_dict(color_dict) +color_from_dict = Color.model_validate(color_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Creature.md b/samples/openapi3/client/petstore/python/docs/Creature.md index a4710214c198..eb0ba3b2f127 100644 --- a/samples/openapi3/client/petstore/python/docs/Creature.md +++ b/samples/openapi3/client/petstore/python/docs/Creature.md @@ -16,14 +16,14 @@ from petstore_api.models.creature import Creature # TODO update the JSON string below json = "{}" # create an instance of Creature from a JSON string -creature_instance = Creature.from_json(json) +creature_instance = Creature.model_validate_json(json) # print the JSON string representation of the object -print(Creature.to_json()) +print(creature_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -creature_dict = creature_instance.to_dict() +creature_dict = creature_instance.model_dump(by_alias=True) # create an instance of Creature from a dict -creature_from_dict = Creature.from_dict(creature_dict) +creature_from_dict = Creature.model_validate(creature_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/CreatureInfo.md b/samples/openapi3/client/petstore/python/docs/CreatureInfo.md index db3b82bb9ff5..156d93939201 100644 --- a/samples/openapi3/client/petstore/python/docs/CreatureInfo.md +++ b/samples/openapi3/client/petstore/python/docs/CreatureInfo.md @@ -15,14 +15,14 @@ from petstore_api.models.creature_info import CreatureInfo # TODO update the JSON string below json = "{}" # create an instance of CreatureInfo from a JSON string -creature_info_instance = CreatureInfo.from_json(json) +creature_info_instance = CreatureInfo.model_validate_json(json) # print the JSON string representation of the object -print(CreatureInfo.to_json()) +print(creature_info_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -creature_info_dict = creature_info_instance.to_dict() +creature_info_dict = creature_info_instance.model_dump(by_alias=True) # create an instance of CreatureInfo from a dict -creature_info_from_dict = CreatureInfo.from_dict(creature_info_dict) +creature_info_from_dict = CreatureInfo.model_validate(creature_info_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/DanishPig.md b/samples/openapi3/client/petstore/python/docs/DanishPig.md index 16941388832a..5eac27f79e79 100644 --- a/samples/openapi3/client/petstore/python/docs/DanishPig.md +++ b/samples/openapi3/client/petstore/python/docs/DanishPig.md @@ -16,14 +16,14 @@ from petstore_api.models.danish_pig import DanishPig # TODO update the JSON string below json = "{}" # create an instance of DanishPig from a JSON string -danish_pig_instance = DanishPig.from_json(json) +danish_pig_instance = DanishPig.model_validate_json(json) # print the JSON string representation of the object -print(DanishPig.to_json()) +print(danish_pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -danish_pig_dict = danish_pig_instance.to_dict() +danish_pig_dict = danish_pig_instance.model_dump(by_alias=True) # create an instance of DanishPig from a dict -danish_pig_from_dict = DanishPig.from_dict(danish_pig_dict) +danish_pig_from_dict = DanishPig.model_validate(danish_pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/DeprecatedObject.md b/samples/openapi3/client/petstore/python/docs/DeprecatedObject.md index 6b362f379ba4..ff3aa9812e2d 100644 --- a/samples/openapi3/client/petstore/python/docs/DeprecatedObject.md +++ b/samples/openapi3/client/petstore/python/docs/DeprecatedObject.md @@ -15,14 +15,14 @@ from petstore_api.models.deprecated_object import DeprecatedObject # TODO update the JSON string below json = "{}" # create an instance of DeprecatedObject from a JSON string -deprecated_object_instance = DeprecatedObject.from_json(json) +deprecated_object_instance = DeprecatedObject.model_validate_json(json) # print the JSON string representation of the object -print(DeprecatedObject.to_json()) +print(deprecated_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -deprecated_object_dict = deprecated_object_instance.to_dict() +deprecated_object_dict = deprecated_object_instance.model_dump(by_alias=True) # create an instance of DeprecatedObject from a dict -deprecated_object_from_dict = DeprecatedObject.from_dict(deprecated_object_dict) +deprecated_object_from_dict = DeprecatedObject.model_validate(deprecated_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/DiscriminatorAllOfSub.md b/samples/openapi3/client/petstore/python/docs/DiscriminatorAllOfSub.md index f72b6e8e68ca..aa7af45b99fa 100644 --- a/samples/openapi3/client/petstore/python/docs/DiscriminatorAllOfSub.md +++ b/samples/openapi3/client/petstore/python/docs/DiscriminatorAllOfSub.md @@ -14,14 +14,14 @@ from petstore_api.models.discriminator_all_of_sub import DiscriminatorAllOfSub # TODO update the JSON string below json = "{}" # create an instance of DiscriminatorAllOfSub from a JSON string -discriminator_all_of_sub_instance = DiscriminatorAllOfSub.from_json(json) +discriminator_all_of_sub_instance = DiscriminatorAllOfSub.model_validate_json(json) # print the JSON string representation of the object -print(DiscriminatorAllOfSub.to_json()) +print(discriminator_all_of_sub_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -discriminator_all_of_sub_dict = discriminator_all_of_sub_instance.to_dict() +discriminator_all_of_sub_dict = discriminator_all_of_sub_instance.model_dump(by_alias=True) # create an instance of DiscriminatorAllOfSub from a dict -discriminator_all_of_sub_from_dict = DiscriminatorAllOfSub.from_dict(discriminator_all_of_sub_dict) +discriminator_all_of_sub_from_dict = DiscriminatorAllOfSub.model_validate(discriminator_all_of_sub_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/DiscriminatorAllOfSuper.md b/samples/openapi3/client/petstore/python/docs/DiscriminatorAllOfSuper.md index 477c05bfc446..c21e5b2296ac 100644 --- a/samples/openapi3/client/petstore/python/docs/DiscriminatorAllOfSuper.md +++ b/samples/openapi3/client/petstore/python/docs/DiscriminatorAllOfSuper.md @@ -15,14 +15,14 @@ from petstore_api.models.discriminator_all_of_super import DiscriminatorAllOfSup # TODO update the JSON string below json = "{}" # create an instance of DiscriminatorAllOfSuper from a JSON string -discriminator_all_of_super_instance = DiscriminatorAllOfSuper.from_json(json) +discriminator_all_of_super_instance = DiscriminatorAllOfSuper.model_validate_json(json) # print the JSON string representation of the object -print(DiscriminatorAllOfSuper.to_json()) +print(discriminator_all_of_super_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -discriminator_all_of_super_dict = discriminator_all_of_super_instance.to_dict() +discriminator_all_of_super_dict = discriminator_all_of_super_instance.model_dump(by_alias=True) # create an instance of DiscriminatorAllOfSuper from a dict -discriminator_all_of_super_from_dict = DiscriminatorAllOfSuper.from_dict(discriminator_all_of_super_dict) +discriminator_all_of_super_from_dict = DiscriminatorAllOfSuper.model_validate(discriminator_all_of_super_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Dog.md b/samples/openapi3/client/petstore/python/docs/Dog.md index ed23f613d01d..2065d42f5f6b 100644 --- a/samples/openapi3/client/petstore/python/docs/Dog.md +++ b/samples/openapi3/client/petstore/python/docs/Dog.md @@ -15,14 +15,14 @@ from petstore_api.models.dog import Dog # TODO update the JSON string below json = "{}" # create an instance of Dog from a JSON string -dog_instance = Dog.from_json(json) +dog_instance = Dog.model_validate_json(json) # print the JSON string representation of the object -print(Dog.to_json()) +print(dog_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -dog_dict = dog_instance.to_dict() +dog_dict = dog_instance.model_dump(by_alias=True) # create an instance of Dog from a dict -dog_from_dict = Dog.from_dict(dog_dict) +dog_from_dict = Dog.model_validate(dog_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/DummyModel.md b/samples/openapi3/client/petstore/python/docs/DummyModel.md index 01b675977f58..dfe28d9f75b1 100644 --- a/samples/openapi3/client/petstore/python/docs/DummyModel.md +++ b/samples/openapi3/client/petstore/python/docs/DummyModel.md @@ -16,14 +16,14 @@ from petstore_api.models.dummy_model import DummyModel # TODO update the JSON string below json = "{}" # create an instance of DummyModel from a JSON string -dummy_model_instance = DummyModel.from_json(json) +dummy_model_instance = DummyModel.model_validate_json(json) # print the JSON string representation of the object -print(DummyModel.to_json()) +print(dummy_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -dummy_model_dict = dummy_model_instance.to_dict() +dummy_model_dict = dummy_model_instance.model_dump(by_alias=True) # create an instance of DummyModel from a dict -dummy_model_from_dict = DummyModel.from_dict(dummy_model_dict) +dummy_model_from_dict = DummyModel.model_validate(dummy_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/EnumArrays.md b/samples/openapi3/client/petstore/python/docs/EnumArrays.md index f44617497bce..bf8b1a6cd05c 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumArrays.md +++ b/samples/openapi3/client/petstore/python/docs/EnumArrays.md @@ -16,14 +16,14 @@ from petstore_api.models.enum_arrays import EnumArrays # TODO update the JSON string below json = "{}" # create an instance of EnumArrays from a JSON string -enum_arrays_instance = EnumArrays.from_json(json) +enum_arrays_instance = EnumArrays.model_validate_json(json) # print the JSON string representation of the object -print(EnumArrays.to_json()) +print(enum_arrays_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_arrays_dict = enum_arrays_instance.to_dict() +enum_arrays_dict = enum_arrays_instance.model_dump(by_alias=True) # create an instance of EnumArrays from a dict -enum_arrays_from_dict = EnumArrays.from_dict(enum_arrays_dict) +enum_arrays_from_dict = EnumArrays.model_validate(enum_arrays_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/EnumRefWithDefaultValue.md b/samples/openapi3/client/petstore/python/docs/EnumRefWithDefaultValue.md index eeb0dc66969f..cbe6845479eb 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumRefWithDefaultValue.md +++ b/samples/openapi3/client/petstore/python/docs/EnumRefWithDefaultValue.md @@ -15,14 +15,14 @@ from petstore_api.models.enum_ref_with_default_value import EnumRefWithDefaultVa # TODO update the JSON string below json = "{}" # create an instance of EnumRefWithDefaultValue from a JSON string -enum_ref_with_default_value_instance = EnumRefWithDefaultValue.from_json(json) +enum_ref_with_default_value_instance = EnumRefWithDefaultValue.model_validate_json(json) # print the JSON string representation of the object -print(EnumRefWithDefaultValue.to_json()) +print(enum_ref_with_default_value_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_ref_with_default_value_dict = enum_ref_with_default_value_instance.to_dict() +enum_ref_with_default_value_dict = enum_ref_with_default_value_instance.model_dump(by_alias=True) # create an instance of EnumRefWithDefaultValue from a dict -enum_ref_with_default_value_from_dict = EnumRefWithDefaultValue.from_dict(enum_ref_with_default_value_dict) +enum_ref_with_default_value_from_dict = EnumRefWithDefaultValue.model_validate(enum_ref_with_default_value_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/EnumTest.md b/samples/openapi3/client/petstore/python/docs/EnumTest.md index 9f96c605d888..6ce4891aa9d5 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumTest.md +++ b/samples/openapi3/client/petstore/python/docs/EnumTest.md @@ -27,14 +27,14 @@ from petstore_api.models.enum_test import EnumTest # TODO update the JSON string below json = "{}" # create an instance of EnumTest from a JSON string -enum_test_instance = EnumTest.from_json(json) +enum_test_instance = EnumTest.model_validate_json(json) # print the JSON string representation of the object -print(EnumTest.to_json()) +print(enum_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -enum_test_dict = enum_test_instance.to_dict() +enum_test_dict = enum_test_instance.model_dump(by_alias=True) # create an instance of EnumTest from a dict -enum_test_from_dict = EnumTest.from_dict(enum_test_dict) +enum_test_from_dict = EnumTest.model_validate(enum_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Feeding.md b/samples/openapi3/client/petstore/python/docs/Feeding.md index 9f92b5d964d3..773d1373cca0 100644 --- a/samples/openapi3/client/petstore/python/docs/Feeding.md +++ b/samples/openapi3/client/petstore/python/docs/Feeding.md @@ -17,14 +17,14 @@ from petstore_api.models.feeding import Feeding # TODO update the JSON string below json = "{}" # create an instance of Feeding from a JSON string -feeding_instance = Feeding.from_json(json) +feeding_instance = Feeding.model_validate_json(json) # print the JSON string representation of the object -print(Feeding.to_json()) +print(feeding_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -feeding_dict = feeding_instance.to_dict() +feeding_dict = feeding_instance.model_dump(by_alias=True) # create an instance of Feeding from a dict -feeding_from_dict = Feeding.from_dict(feeding_dict) +feeding_from_dict = Feeding.model_validate(feeding_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/File.md b/samples/openapi3/client/petstore/python/docs/File.md index 23f0567411ce..3fe748f4f30f 100644 --- a/samples/openapi3/client/petstore/python/docs/File.md +++ b/samples/openapi3/client/petstore/python/docs/File.md @@ -16,14 +16,14 @@ from petstore_api.models.file import File # TODO update the JSON string below json = "{}" # create an instance of File from a JSON string -file_instance = File.from_json(json) +file_instance = File.model_validate_json(json) # print the JSON string representation of the object -print(File.to_json()) +print(file_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -file_dict = file_instance.to_dict() +file_dict = file_instance.model_dump(by_alias=True) # create an instance of File from a dict -file_from_dict = File.from_dict(file_dict) +file_from_dict = File.model_validate(file_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md index e1118042a8ec..78bc4ae135da 100644 --- a/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md +++ b/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md @@ -16,14 +16,14 @@ from petstore_api.models.file_schema_test_class import FileSchemaTestClass # TODO update the JSON string below json = "{}" # create an instance of FileSchemaTestClass from a JSON string -file_schema_test_class_instance = FileSchemaTestClass.from_json(json) +file_schema_test_class_instance = FileSchemaTestClass.model_validate_json(json) # print the JSON string representation of the object -print(FileSchemaTestClass.to_json()) +print(file_schema_test_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -file_schema_test_class_dict = file_schema_test_class_instance.to_dict() +file_schema_test_class_dict = file_schema_test_class_instance.model_dump(by_alias=True) # create an instance of FileSchemaTestClass from a dict -file_schema_test_class_from_dict = FileSchemaTestClass.from_dict(file_schema_test_class_dict) +file_schema_test_class_from_dict = FileSchemaTestClass.model_validate(file_schema_test_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/FirstRef.md b/samples/openapi3/client/petstore/python/docs/FirstRef.md index 94b8ddc5ac22..6da6650e5df7 100644 --- a/samples/openapi3/client/petstore/python/docs/FirstRef.md +++ b/samples/openapi3/client/petstore/python/docs/FirstRef.md @@ -16,14 +16,14 @@ from petstore_api.models.first_ref import FirstRef # TODO update the JSON string below json = "{}" # create an instance of FirstRef from a JSON string -first_ref_instance = FirstRef.from_json(json) +first_ref_instance = FirstRef.model_validate_json(json) # print the JSON string representation of the object -print(FirstRef.to_json()) +print(first_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -first_ref_dict = first_ref_instance.to_dict() +first_ref_dict = first_ref_instance.model_dump(by_alias=True) # create an instance of FirstRef from a dict -first_ref_from_dict = FirstRef.from_dict(first_ref_dict) +first_ref_from_dict = FirstRef.model_validate(first_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Foo.md b/samples/openapi3/client/petstore/python/docs/Foo.md index f635b0daa6db..c11ae111ee22 100644 --- a/samples/openapi3/client/petstore/python/docs/Foo.md +++ b/samples/openapi3/client/petstore/python/docs/Foo.md @@ -15,14 +15,14 @@ from petstore_api.models.foo import Foo # TODO update the JSON string below json = "{}" # create an instance of Foo from a JSON string -foo_instance = Foo.from_json(json) +foo_instance = Foo.model_validate_json(json) # print the JSON string representation of the object -print(Foo.to_json()) +print(foo_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -foo_dict = foo_instance.to_dict() +foo_dict = foo_instance.model_dump(by_alias=True) # create an instance of Foo from a dict -foo_from_dict = Foo.from_dict(foo_dict) +foo_from_dict = Foo.model_validate(foo_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md b/samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md index 8d84f795b00a..aaccf08bfd2e 100644 --- a/samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md +++ b/samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md @@ -15,14 +15,14 @@ from petstore_api.models.foo_get_default_response import FooGetDefaultResponse # TODO update the JSON string below json = "{}" # create an instance of FooGetDefaultResponse from a JSON string -foo_get_default_response_instance = FooGetDefaultResponse.from_json(json) +foo_get_default_response_instance = FooGetDefaultResponse.model_validate_json(json) # print the JSON string representation of the object -print(FooGetDefaultResponse.to_json()) +print(foo_get_default_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -foo_get_default_response_dict = foo_get_default_response_instance.to_dict() +foo_get_default_response_dict = foo_get_default_response_instance.model_dump(by_alias=True) # create an instance of FooGetDefaultResponse from a dict -foo_get_default_response_from_dict = FooGetDefaultResponse.from_dict(foo_get_default_response_dict) +foo_get_default_response_from_dict = FooGetDefaultResponse.model_validate(foo_get_default_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/FormatTest.md b/samples/openapi3/client/petstore/python/docs/FormatTest.md index 714d2401bbae..98c3dc89570d 100644 --- a/samples/openapi3/client/petstore/python/docs/FormatTest.md +++ b/samples/openapi3/client/petstore/python/docs/FormatTest.md @@ -31,14 +31,14 @@ from petstore_api.models.format_test import FormatTest # TODO update the JSON string below json = "{}" # create an instance of FormatTest from a JSON string -format_test_instance = FormatTest.from_json(json) +format_test_instance = FormatTest.model_validate_json(json) # print the JSON string representation of the object -print(FormatTest.to_json()) +print(format_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -format_test_dict = format_test_instance.to_dict() +format_test_dict = format_test_instance.model_dump(by_alias=True) # create an instance of FormatTest from a dict -format_test_from_dict = FormatTest.from_dict(format_test_dict) +format_test_from_dict = FormatTest.model_validate(format_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md index fdc48781b15a..66dca11251aa 100644 --- a/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md +++ b/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md @@ -16,14 +16,14 @@ from petstore_api.models.has_only_read_only import HasOnlyReadOnly # TODO update the JSON string below json = "{}" # create an instance of HasOnlyReadOnly from a JSON string -has_only_read_only_instance = HasOnlyReadOnly.from_json(json) +has_only_read_only_instance = HasOnlyReadOnly.model_validate_json(json) # print the JSON string representation of the object -print(HasOnlyReadOnly.to_json()) +print(has_only_read_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -has_only_read_only_dict = has_only_read_only_instance.to_dict() +has_only_read_only_dict = has_only_read_only_instance.model_dump(by_alias=True) # create an instance of HasOnlyReadOnly from a dict -has_only_read_only_from_dict = HasOnlyReadOnly.from_dict(has_only_read_only_dict) +has_only_read_only_from_dict = HasOnlyReadOnly.model_validate(has_only_read_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md index d4a2b187167f..522156ae5b16 100644 --- a/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md +++ b/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md @@ -16,14 +16,14 @@ from petstore_api.models.health_check_result import HealthCheckResult # TODO update the JSON string below json = "{}" # create an instance of HealthCheckResult from a JSON string -health_check_result_instance = HealthCheckResult.from_json(json) +health_check_result_instance = HealthCheckResult.model_validate_json(json) # print the JSON string representation of the object -print(HealthCheckResult.to_json()) +print(health_check_result_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -health_check_result_dict = health_check_result_instance.to_dict() +health_check_result_dict = health_check_result_instance.model_dump(by_alias=True) # create an instance of HealthCheckResult from a dict -health_check_result_from_dict = HealthCheckResult.from_dict(health_check_result_dict) +health_check_result_from_dict = HealthCheckResult.model_validate(health_check_result_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/HuntingDog.md b/samples/openapi3/client/petstore/python/docs/HuntingDog.md index 6db6745dd022..114dfc8575d9 100644 --- a/samples/openapi3/client/petstore/python/docs/HuntingDog.md +++ b/samples/openapi3/client/petstore/python/docs/HuntingDog.md @@ -15,14 +15,14 @@ from petstore_api.models.hunting_dog import HuntingDog # TODO update the JSON string below json = "{}" # create an instance of HuntingDog from a JSON string -hunting_dog_instance = HuntingDog.from_json(json) +hunting_dog_instance = HuntingDog.model_validate_json(json) # print the JSON string representation of the object -print(HuntingDog.to_json()) +print(hunting_dog_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -hunting_dog_dict = hunting_dog_instance.to_dict() +hunting_dog_dict = hunting_dog_instance.model_dump(by_alias=True) # create an instance of HuntingDog from a dict -hunting_dog_from_dict = HuntingDog.from_dict(hunting_dog_dict) +hunting_dog_from_dict = HuntingDog.model_validate(hunting_dog_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Info.md b/samples/openapi3/client/petstore/python/docs/Info.md index db88778a9143..160c3633247c 100644 --- a/samples/openapi3/client/petstore/python/docs/Info.md +++ b/samples/openapi3/client/petstore/python/docs/Info.md @@ -15,14 +15,14 @@ from petstore_api.models.info import Info # TODO update the JSON string below json = "{}" # create an instance of Info from a JSON string -info_instance = Info.from_json(json) +info_instance = Info.model_validate_json(json) # print the JSON string representation of the object -print(Info.to_json()) +print(info_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -info_dict = info_instance.to_dict() +info_dict = info_instance.model_dump(by_alias=True) # create an instance of Info from a dict -info_from_dict = Info.from_dict(info_dict) +info_from_dict = Info.model_validate(info_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/InnerDictWithProperty.md b/samples/openapi3/client/petstore/python/docs/InnerDictWithProperty.md index 7b82ebb770b8..79234d754027 100644 --- a/samples/openapi3/client/petstore/python/docs/InnerDictWithProperty.md +++ b/samples/openapi3/client/petstore/python/docs/InnerDictWithProperty.md @@ -15,14 +15,14 @@ from petstore_api.models.inner_dict_with_property import InnerDictWithProperty # TODO update the JSON string below json = "{}" # create an instance of InnerDictWithProperty from a JSON string -inner_dict_with_property_instance = InnerDictWithProperty.from_json(json) +inner_dict_with_property_instance = InnerDictWithProperty.model_validate_json(json) # print the JSON string representation of the object -print(InnerDictWithProperty.to_json()) +print(inner_dict_with_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -inner_dict_with_property_dict = inner_dict_with_property_instance.to_dict() +inner_dict_with_property_dict = inner_dict_with_property_instance.model_dump(by_alias=True) # create an instance of InnerDictWithProperty from a dict -inner_dict_with_property_from_dict = InnerDictWithProperty.from_dict(inner_dict_with_property_dict) +inner_dict_with_property_from_dict = InnerDictWithProperty.model_validate(inner_dict_with_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/InputAllOf.md b/samples/openapi3/client/petstore/python/docs/InputAllOf.md index 45298f5308fc..32d4100ac9de 100644 --- a/samples/openapi3/client/petstore/python/docs/InputAllOf.md +++ b/samples/openapi3/client/petstore/python/docs/InputAllOf.md @@ -15,14 +15,14 @@ from petstore_api.models.input_all_of import InputAllOf # TODO update the JSON string below json = "{}" # create an instance of InputAllOf from a JSON string -input_all_of_instance = InputAllOf.from_json(json) +input_all_of_instance = InputAllOf.model_validate_json(json) # print the JSON string representation of the object -print(InputAllOf.to_json()) +print(input_all_of_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -input_all_of_dict = input_all_of_instance.to_dict() +input_all_of_dict = input_all_of_instance.model_dump(by_alias=True) # create an instance of InputAllOf from a dict -input_all_of_from_dict = InputAllOf.from_dict(input_all_of_dict) +input_all_of_from_dict = InputAllOf.model_validate(input_all_of_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/IntOrString.md b/samples/openapi3/client/petstore/python/docs/IntOrString.md index b4070b9a8c79..ea8e06339493 100644 --- a/samples/openapi3/client/petstore/python/docs/IntOrString.md +++ b/samples/openapi3/client/petstore/python/docs/IntOrString.md @@ -14,14 +14,14 @@ from petstore_api.models.int_or_string import IntOrString # TODO update the JSON string below json = "{}" # create an instance of IntOrString from a JSON string -int_or_string_instance = IntOrString.from_json(json) +int_or_string_instance = IntOrString.model_validate_json(json) # print the JSON string representation of the object -print(IntOrString.to_json()) +print(int_or_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -int_or_string_dict = int_or_string_instance.to_dict() +int_or_string_dict = int_or_string_instance.model_dump(by_alias=True) # create an instance of IntOrString from a dict -int_or_string_from_dict = IntOrString.from_dict(int_or_string_dict) +int_or_string_from_dict = IntOrString.model_validate(int_or_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ListClass.md b/samples/openapi3/client/petstore/python/docs/ListClass.md index 01068b7d22c3..8bc905105efe 100644 --- a/samples/openapi3/client/petstore/python/docs/ListClass.md +++ b/samples/openapi3/client/petstore/python/docs/ListClass.md @@ -15,14 +15,14 @@ from petstore_api.models.list_class import ListClass # TODO update the JSON string below json = "{}" # create an instance of ListClass from a JSON string -list_class_instance = ListClass.from_json(json) +list_class_instance = ListClass.model_validate_json(json) # print the JSON string representation of the object -print(ListClass.to_json()) +print(list_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -list_class_dict = list_class_instance.to_dict() +list_class_dict = list_class_instance.model_dump(by_alias=True) # create an instance of ListClass from a dict -list_class_from_dict = ListClass.from_dict(list_class_dict) +list_class_from_dict = ListClass.model_validate(list_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/MapOfArrayOfModel.md b/samples/openapi3/client/petstore/python/docs/MapOfArrayOfModel.md index 71a4ef66b682..acea13d9a9f5 100644 --- a/samples/openapi3/client/petstore/python/docs/MapOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python/docs/MapOfArrayOfModel.md @@ -15,14 +15,14 @@ from petstore_api.models.map_of_array_of_model import MapOfArrayOfModel # TODO update the JSON string below json = "{}" # create an instance of MapOfArrayOfModel from a JSON string -map_of_array_of_model_instance = MapOfArrayOfModel.from_json(json) +map_of_array_of_model_instance = MapOfArrayOfModel.model_validate_json(json) # print the JSON string representation of the object -print(MapOfArrayOfModel.to_json()) +print(map_of_array_of_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -map_of_array_of_model_dict = map_of_array_of_model_instance.to_dict() +map_of_array_of_model_dict = map_of_array_of_model_instance.model_dump(by_alias=True) # create an instance of MapOfArrayOfModel from a dict -map_of_array_of_model_from_dict = MapOfArrayOfModel.from_dict(map_of_array_of_model_dict) +map_of_array_of_model_from_dict = MapOfArrayOfModel.model_validate(map_of_array_of_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/MapTest.md b/samples/openapi3/client/petstore/python/docs/MapTest.md index d04b82e9378c..fa4501d24286 100644 --- a/samples/openapi3/client/petstore/python/docs/MapTest.md +++ b/samples/openapi3/client/petstore/python/docs/MapTest.md @@ -18,14 +18,14 @@ from petstore_api.models.map_test import MapTest # TODO update the JSON string below json = "{}" # create an instance of MapTest from a JSON string -map_test_instance = MapTest.from_json(json) +map_test_instance = MapTest.model_validate_json(json) # print the JSON string representation of the object -print(MapTest.to_json()) +print(map_test_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -map_test_dict = map_test_instance.to_dict() +map_test_dict = map_test_instance.model_dump(by_alias=True) # create an instance of MapTest from a dict -map_test_from_dict = MapTest.from_dict(map_test_dict) +map_test_from_dict = MapTest.model_validate(map_test_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md index 84134317aefc..fb354956720a 100644 --- a/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -17,14 +17,14 @@ from petstore_api.models.mixed_properties_and_additional_properties_class import # TODO update the JSON string below json = "{}" # create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string -mixed_properties_and_additional_properties_class_instance = MixedPropertiesAndAdditionalPropertiesClass.from_json(json) +mixed_properties_and_additional_properties_class_instance = MixedPropertiesAndAdditionalPropertiesClass.model_validate_json(json) # print the JSON string representation of the object -print(MixedPropertiesAndAdditionalPropertiesClass.to_json()) +print(mixed_properties_and_additional_properties_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -mixed_properties_and_additional_properties_class_dict = mixed_properties_and_additional_properties_class_instance.to_dict() +mixed_properties_and_additional_properties_class_dict = mixed_properties_and_additional_properties_class_instance.model_dump(by_alias=True) # create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict -mixed_properties_and_additional_properties_class_from_dict = MixedPropertiesAndAdditionalPropertiesClass.from_dict(mixed_properties_and_additional_properties_class_dict) +mixed_properties_and_additional_properties_class_from_dict = MixedPropertiesAndAdditionalPropertiesClass.model_validate(mixed_properties_and_additional_properties_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Model200Response.md b/samples/openapi3/client/petstore/python/docs/Model200Response.md index 7fdbdefc6cec..6cffad7a6d3a 100644 --- a/samples/openapi3/client/petstore/python/docs/Model200Response.md +++ b/samples/openapi3/client/petstore/python/docs/Model200Response.md @@ -17,14 +17,14 @@ from petstore_api.models.model200_response import Model200Response # TODO update the JSON string below json = "{}" # create an instance of Model200Response from a JSON string -model200_response_instance = Model200Response.from_json(json) +model200_response_instance = Model200Response.model_validate_json(json) # print the JSON string representation of the object -print(Model200Response.to_json()) +print(model200_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model200_response_dict = model200_response_instance.to_dict() +model200_response_dict = model200_response_instance.model_dump(by_alias=True) # create an instance of Model200Response from a dict -model200_response_from_dict = Model200Response.from_dict(model200_response_dict) +model200_response_from_dict = Model200Response.model_validate(model200_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ModelApiResponse.md b/samples/openapi3/client/petstore/python/docs/ModelApiResponse.md index 5ddc0db2a0f3..4fdaa910bce4 100644 --- a/samples/openapi3/client/petstore/python/docs/ModelApiResponse.md +++ b/samples/openapi3/client/petstore/python/docs/ModelApiResponse.md @@ -17,14 +17,14 @@ from petstore_api.models.model_api_response import ModelApiResponse # TODO update the JSON string below json = "{}" # create an instance of ModelApiResponse from a JSON string -model_api_response_instance = ModelApiResponse.from_json(json) +model_api_response_instance = ModelApiResponse.model_validate_json(json) # print the JSON string representation of the object -print(ModelApiResponse.to_json()) +print(model_api_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_api_response_dict = model_api_response_instance.to_dict() +model_api_response_dict = model_api_response_instance.model_dump(by_alias=True) # create an instance of ModelApiResponse from a dict -model_api_response_from_dict = ModelApiResponse.from_dict(model_api_response_dict) +model_api_response_from_dict = ModelApiResponse.model_validate(model_api_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ModelField.md b/samples/openapi3/client/petstore/python/docs/ModelField.md index 9073b5dbdb00..43f064bd85a4 100644 --- a/samples/openapi3/client/petstore/python/docs/ModelField.md +++ b/samples/openapi3/client/petstore/python/docs/ModelField.md @@ -15,14 +15,14 @@ from petstore_api.models.model_field import ModelField # TODO update the JSON string below json = "{}" # create an instance of ModelField from a JSON string -model_field_instance = ModelField.from_json(json) +model_field_instance = ModelField.model_validate_json(json) # print the JSON string representation of the object -print(ModelField.to_json()) +print(model_field_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_field_dict = model_field_instance.to_dict() +model_field_dict = model_field_instance.model_dump(by_alias=True) # create an instance of ModelField from a dict -model_field_from_dict = ModelField.from_dict(model_field_dict) +model_field_from_dict = ModelField.model_validate(model_field_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ModelReturn.md b/samples/openapi3/client/petstore/python/docs/ModelReturn.md index 7d327053b0c3..236b2bb971ee 100644 --- a/samples/openapi3/client/petstore/python/docs/ModelReturn.md +++ b/samples/openapi3/client/petstore/python/docs/ModelReturn.md @@ -16,14 +16,14 @@ from petstore_api.models.model_return import ModelReturn # TODO update the JSON string below json = "{}" # create an instance of ModelReturn from a JSON string -model_return_instance = ModelReturn.from_json(json) +model_return_instance = ModelReturn.model_validate_json(json) # print the JSON string representation of the object -print(ModelReturn.to_json()) +print(model_return_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -model_return_dict = model_return_instance.to_dict() +model_return_dict = model_return_instance.model_dump(by_alias=True) # create an instance of ModelReturn from a dict -model_return_from_dict = ModelReturn.from_dict(model_return_dict) +model_return_from_dict = ModelReturn.model_validate(model_return_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/MultiArrays.md b/samples/openapi3/client/petstore/python/docs/MultiArrays.md index fea5139e7e73..9cf5c5bb1faa 100644 --- a/samples/openapi3/client/petstore/python/docs/MultiArrays.md +++ b/samples/openapi3/client/petstore/python/docs/MultiArrays.md @@ -16,14 +16,14 @@ from petstore_api.models.multi_arrays import MultiArrays # TODO update the JSON string below json = "{}" # create an instance of MultiArrays from a JSON string -multi_arrays_instance = MultiArrays.from_json(json) +multi_arrays_instance = MultiArrays.model_validate_json(json) # print the JSON string representation of the object -print(MultiArrays.to_json()) +print(multi_arrays_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -multi_arrays_dict = multi_arrays_instance.to_dict() +multi_arrays_dict = multi_arrays_instance.model_dump(by_alias=True) # create an instance of MultiArrays from a dict -multi_arrays_from_dict = MultiArrays.from_dict(multi_arrays_dict) +multi_arrays_from_dict = MultiArrays.model_validate(multi_arrays_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Name.md b/samples/openapi3/client/petstore/python/docs/Name.md index 5a04ec1ada06..f9d2da4cccd2 100644 --- a/samples/openapi3/client/petstore/python/docs/Name.md +++ b/samples/openapi3/client/petstore/python/docs/Name.md @@ -19,14 +19,14 @@ from petstore_api.models.name import Name # TODO update the JSON string below json = "{}" # create an instance of Name from a JSON string -name_instance = Name.from_json(json) +name_instance = Name.model_validate_json(json) # print the JSON string representation of the object -print(Name.to_json()) +print(name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -name_dict = name_instance.to_dict() +name_dict = name_instance.model_dump(by_alias=True) # create an instance of Name from a dict -name_from_dict = Name.from_dict(name_dict) +name_from_dict = Name.model_validate(name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/NullableClass.md b/samples/openapi3/client/petstore/python/docs/NullableClass.md index 0387dcc2c67a..cd84aa96eb19 100644 --- a/samples/openapi3/client/petstore/python/docs/NullableClass.md +++ b/samples/openapi3/client/petstore/python/docs/NullableClass.md @@ -27,14 +27,14 @@ from petstore_api.models.nullable_class import NullableClass # TODO update the JSON string below json = "{}" # create an instance of NullableClass from a JSON string -nullable_class_instance = NullableClass.from_json(json) +nullable_class_instance = NullableClass.model_validate_json(json) # print the JSON string representation of the object -print(NullableClass.to_json()) +print(nullable_class_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -nullable_class_dict = nullable_class_instance.to_dict() +nullable_class_dict = nullable_class_instance.model_dump(by_alias=True) # create an instance of NullableClass from a dict -nullable_class_from_dict = NullableClass.from_dict(nullable_class_dict) +nullable_class_from_dict = NullableClass.model_validate(nullable_class_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/NullableProperty.md b/samples/openapi3/client/petstore/python/docs/NullableProperty.md index 30edaf4844b2..c0ef9b80fcb5 100644 --- a/samples/openapi3/client/petstore/python/docs/NullableProperty.md +++ b/samples/openapi3/client/petstore/python/docs/NullableProperty.md @@ -16,14 +16,14 @@ from petstore_api.models.nullable_property import NullableProperty # TODO update the JSON string below json = "{}" # create an instance of NullableProperty from a JSON string -nullable_property_instance = NullableProperty.from_json(json) +nullable_property_instance = NullableProperty.model_validate_json(json) # print the JSON string representation of the object -print(NullableProperty.to_json()) +print(nullable_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -nullable_property_dict = nullable_property_instance.to_dict() +nullable_property_dict = nullable_property_instance.model_dump(by_alias=True) # create an instance of NullableProperty from a dict -nullable_property_from_dict = NullableProperty.from_dict(nullable_property_dict) +nullable_property_from_dict = NullableProperty.model_validate(nullable_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/NumberOnly.md b/samples/openapi3/client/petstore/python/docs/NumberOnly.md index 415dd25585d4..f1caf70ea2b7 100644 --- a/samples/openapi3/client/petstore/python/docs/NumberOnly.md +++ b/samples/openapi3/client/petstore/python/docs/NumberOnly.md @@ -15,14 +15,14 @@ from petstore_api.models.number_only import NumberOnly # TODO update the JSON string below json = "{}" # create an instance of NumberOnly from a JSON string -number_only_instance = NumberOnly.from_json(json) +number_only_instance = NumberOnly.model_validate_json(json) # print the JSON string representation of the object -print(NumberOnly.to_json()) +print(number_only_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -number_only_dict = number_only_instance.to_dict() +number_only_dict = number_only_instance.model_dump(by_alias=True) # create an instance of NumberOnly from a dict -number_only_from_dict = NumberOnly.from_dict(number_only_dict) +number_only_from_dict = NumberOnly.model_validate(number_only_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ObjectToTestAdditionalProperties.md b/samples/openapi3/client/petstore/python/docs/ObjectToTestAdditionalProperties.md index f6bc34c98e65..f201a9627dc3 100644 --- a/samples/openapi3/client/petstore/python/docs/ObjectToTestAdditionalProperties.md +++ b/samples/openapi3/client/petstore/python/docs/ObjectToTestAdditionalProperties.md @@ -16,14 +16,14 @@ from petstore_api.models.object_to_test_additional_properties import ObjectToTes # TODO update the JSON string below json = "{}" # create an instance of ObjectToTestAdditionalProperties from a JSON string -object_to_test_additional_properties_instance = ObjectToTestAdditionalProperties.from_json(json) +object_to_test_additional_properties_instance = ObjectToTestAdditionalProperties.model_validate_json(json) # print the JSON string representation of the object -print(ObjectToTestAdditionalProperties.to_json()) +print(object_to_test_additional_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -object_to_test_additional_properties_dict = object_to_test_additional_properties_instance.to_dict() +object_to_test_additional_properties_dict = object_to_test_additional_properties_instance.model_dump(by_alias=True) # create an instance of ObjectToTestAdditionalProperties from a dict -object_to_test_additional_properties_from_dict = ObjectToTestAdditionalProperties.from_dict(object_to_test_additional_properties_dict) +object_to_test_additional_properties_from_dict = ObjectToTestAdditionalProperties.model_validate(object_to_test_additional_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ObjectWithDeprecatedFields.md b/samples/openapi3/client/petstore/python/docs/ObjectWithDeprecatedFields.md index 6dbd2ace04f1..86cce93ba775 100644 --- a/samples/openapi3/client/petstore/python/docs/ObjectWithDeprecatedFields.md +++ b/samples/openapi3/client/petstore/python/docs/ObjectWithDeprecatedFields.md @@ -18,14 +18,14 @@ from petstore_api.models.object_with_deprecated_fields import ObjectWithDeprecat # TODO update the JSON string below json = "{}" # create an instance of ObjectWithDeprecatedFields from a JSON string -object_with_deprecated_fields_instance = ObjectWithDeprecatedFields.from_json(json) +object_with_deprecated_fields_instance = ObjectWithDeprecatedFields.model_validate_json(json) # print the JSON string representation of the object -print(ObjectWithDeprecatedFields.to_json()) +print(object_with_deprecated_fields_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -object_with_deprecated_fields_dict = object_with_deprecated_fields_instance.to_dict() +object_with_deprecated_fields_dict = object_with_deprecated_fields_instance.model_dump(by_alias=True) # create an instance of ObjectWithDeprecatedFields from a dict -object_with_deprecated_fields_from_dict = ObjectWithDeprecatedFields.from_dict(object_with_deprecated_fields_dict) +object_with_deprecated_fields_from_dict = ObjectWithDeprecatedFields.model_validate(object_with_deprecated_fields_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/OneOfEnumString.md b/samples/openapi3/client/petstore/python/docs/OneOfEnumString.md index 1d385c092934..69f4f99d32e4 100644 --- a/samples/openapi3/client/petstore/python/docs/OneOfEnumString.md +++ b/samples/openapi3/client/petstore/python/docs/OneOfEnumString.md @@ -15,14 +15,14 @@ from petstore_api.models.one_of_enum_string import OneOfEnumString # TODO update the JSON string below json = "{}" # create an instance of OneOfEnumString from a JSON string -one_of_enum_string_instance = OneOfEnumString.from_json(json) +one_of_enum_string_instance = OneOfEnumString.model_validate_json(json) # print the JSON string representation of the object -print(OneOfEnumString.to_json()) +print(one_of_enum_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -one_of_enum_string_dict = one_of_enum_string_instance.to_dict() +one_of_enum_string_dict = one_of_enum_string_instance.model_dump(by_alias=True) # create an instance of OneOfEnumString from a dict -one_of_enum_string_from_dict = OneOfEnumString.from_dict(one_of_enum_string_dict) +one_of_enum_string_from_dict = OneOfEnumString.model_validate(one_of_enum_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Order.md b/samples/openapi3/client/petstore/python/docs/Order.md index 00526b8d04b9..f5410bc8d0f3 100644 --- a/samples/openapi3/client/petstore/python/docs/Order.md +++ b/samples/openapi3/client/petstore/python/docs/Order.md @@ -20,14 +20,14 @@ from petstore_api.models.order import Order # TODO update the JSON string below json = "{}" # create an instance of Order from a JSON string -order_instance = Order.from_json(json) +order_instance = Order.model_validate_json(json) # print the JSON string representation of the object -print(Order.to_json()) +print(order_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -order_dict = order_instance.to_dict() +order_dict = order_instance.model_dump(by_alias=True) # create an instance of Order from a dict -order_from_dict = Order.from_dict(order_dict) +order_from_dict = Order.model_validate(order_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/OuterComposite.md b/samples/openapi3/client/petstore/python/docs/OuterComposite.md index c8242c2d2653..9df82e2abc87 100644 --- a/samples/openapi3/client/petstore/python/docs/OuterComposite.md +++ b/samples/openapi3/client/petstore/python/docs/OuterComposite.md @@ -17,14 +17,14 @@ from petstore_api.models.outer_composite import OuterComposite # TODO update the JSON string below json = "{}" # create an instance of OuterComposite from a JSON string -outer_composite_instance = OuterComposite.from_json(json) +outer_composite_instance = OuterComposite.model_validate_json(json) # print the JSON string representation of the object -print(OuterComposite.to_json()) +print(outer_composite_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -outer_composite_dict = outer_composite_instance.to_dict() +outer_composite_dict = outer_composite_instance.model_dump(by_alias=True) # create an instance of OuterComposite from a dict -outer_composite_from_dict = OuterComposite.from_dict(outer_composite_dict) +outer_composite_from_dict = OuterComposite.model_validate(outer_composite_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/OuterObjectWithEnumProperty.md b/samples/openapi3/client/petstore/python/docs/OuterObjectWithEnumProperty.md index 6137dbd98da6..d23ccc3757bb 100644 --- a/samples/openapi3/client/petstore/python/docs/OuterObjectWithEnumProperty.md +++ b/samples/openapi3/client/petstore/python/docs/OuterObjectWithEnumProperty.md @@ -16,14 +16,14 @@ from petstore_api.models.outer_object_with_enum_property import OuterObjectWithE # TODO update the JSON string below json = "{}" # create an instance of OuterObjectWithEnumProperty from a JSON string -outer_object_with_enum_property_instance = OuterObjectWithEnumProperty.from_json(json) +outer_object_with_enum_property_instance = OuterObjectWithEnumProperty.model_validate_json(json) # print the JSON string representation of the object -print(OuterObjectWithEnumProperty.to_json()) +print(outer_object_with_enum_property_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -outer_object_with_enum_property_dict = outer_object_with_enum_property_instance.to_dict() +outer_object_with_enum_property_dict = outer_object_with_enum_property_instance.model_dump(by_alias=True) # create an instance of OuterObjectWithEnumProperty from a dict -outer_object_with_enum_property_from_dict = OuterObjectWithEnumProperty.from_dict(outer_object_with_enum_property_dict) +outer_object_with_enum_property_from_dict = OuterObjectWithEnumProperty.model_validate(outer_object_with_enum_property_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Parent.md b/samples/openapi3/client/petstore/python/docs/Parent.md index 7387f9250aad..21df089ea756 100644 --- a/samples/openapi3/client/petstore/python/docs/Parent.md +++ b/samples/openapi3/client/petstore/python/docs/Parent.md @@ -15,14 +15,14 @@ from petstore_api.models.parent import Parent # TODO update the JSON string below json = "{}" # create an instance of Parent from a JSON string -parent_instance = Parent.from_json(json) +parent_instance = Parent.model_validate_json(json) # print the JSON string representation of the object -print(Parent.to_json()) +print(parent_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -parent_dict = parent_instance.to_dict() +parent_dict = parent_instance.model_dump(by_alias=True) # create an instance of Parent from a dict -parent_from_dict = Parent.from_dict(parent_dict) +parent_from_dict = Parent.model_validate(parent_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ParentWithOptionalDict.md b/samples/openapi3/client/petstore/python/docs/ParentWithOptionalDict.md index bfc8688ea26f..a6ee19fd1a74 100644 --- a/samples/openapi3/client/petstore/python/docs/ParentWithOptionalDict.md +++ b/samples/openapi3/client/petstore/python/docs/ParentWithOptionalDict.md @@ -15,14 +15,14 @@ from petstore_api.models.parent_with_optional_dict import ParentWithOptionalDict # TODO update the JSON string below json = "{}" # create an instance of ParentWithOptionalDict from a JSON string -parent_with_optional_dict_instance = ParentWithOptionalDict.from_json(json) +parent_with_optional_dict_instance = ParentWithOptionalDict.model_validate_json(json) # print the JSON string representation of the object -print(ParentWithOptionalDict.to_json()) +print(parent_with_optional_dict_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -parent_with_optional_dict_dict = parent_with_optional_dict_instance.to_dict() +parent_with_optional_dict_dict = parent_with_optional_dict_instance.model_dump(by_alias=True) # create an instance of ParentWithOptionalDict from a dict -parent_with_optional_dict_from_dict = ParentWithOptionalDict.from_dict(parent_with_optional_dict_dict) +parent_with_optional_dict_from_dict = ParentWithOptionalDict.model_validate(parent_with_optional_dict_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Pet.md b/samples/openapi3/client/petstore/python/docs/Pet.md index 5329cf2fb925..179b71891d9d 100644 --- a/samples/openapi3/client/petstore/python/docs/Pet.md +++ b/samples/openapi3/client/petstore/python/docs/Pet.md @@ -20,14 +20,14 @@ from petstore_api.models.pet import Pet # TODO update the JSON string below json = "{}" # create an instance of Pet from a JSON string -pet_instance = Pet.from_json(json) +pet_instance = Pet.model_validate_json(json) # print the JSON string representation of the object -print(Pet.to_json()) +print(pet_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pet_dict = pet_instance.to_dict() +pet_dict = pet_instance.model_dump(by_alias=True) # create an instance of Pet from a dict -pet_from_dict = Pet.from_dict(pet_dict) +pet_from_dict = Pet.model_validate(pet_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Pig.md b/samples/openapi3/client/petstore/python/docs/Pig.md index 625930676083..2e275198c547 100644 --- a/samples/openapi3/client/petstore/python/docs/Pig.md +++ b/samples/openapi3/client/petstore/python/docs/Pig.md @@ -17,14 +17,14 @@ from petstore_api.models.pig import Pig # TODO update the JSON string below json = "{}" # create an instance of Pig from a JSON string -pig_instance = Pig.from_json(json) +pig_instance = Pig.model_validate_json(json) # print the JSON string representation of the object -print(Pig.to_json()) +print(pig_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pig_dict = pig_instance.to_dict() +pig_dict = pig_instance.model_dump(by_alias=True) # create an instance of Pig from a dict -pig_from_dict = Pig.from_dict(pig_dict) +pig_from_dict = Pig.model_validate(pig_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/PonySizes.md b/samples/openapi3/client/petstore/python/docs/PonySizes.md index ced44c872060..6bb28b418b6d 100644 --- a/samples/openapi3/client/petstore/python/docs/PonySizes.md +++ b/samples/openapi3/client/petstore/python/docs/PonySizes.md @@ -15,14 +15,14 @@ from petstore_api.models.pony_sizes import PonySizes # TODO update the JSON string below json = "{}" # create an instance of PonySizes from a JSON string -pony_sizes_instance = PonySizes.from_json(json) +pony_sizes_instance = PonySizes.model_validate_json(json) # print the JSON string representation of the object -print(PonySizes.to_json()) +print(pony_sizes_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -pony_sizes_dict = pony_sizes_instance.to_dict() +pony_sizes_dict = pony_sizes_instance.model_dump(by_alias=True) # create an instance of PonySizes from a dict -pony_sizes_from_dict = PonySizes.from_dict(pony_sizes_dict) +pony_sizes_from_dict = PonySizes.model_validate(pony_sizes_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/PoopCleaning.md b/samples/openapi3/client/petstore/python/docs/PoopCleaning.md index 8f9c25e08316..3bf20593f929 100644 --- a/samples/openapi3/client/petstore/python/docs/PoopCleaning.md +++ b/samples/openapi3/client/petstore/python/docs/PoopCleaning.md @@ -17,14 +17,14 @@ from petstore_api.models.poop_cleaning import PoopCleaning # TODO update the JSON string below json = "{}" # create an instance of PoopCleaning from a JSON string -poop_cleaning_instance = PoopCleaning.from_json(json) +poop_cleaning_instance = PoopCleaning.model_validate_json(json) # print the JSON string representation of the object -print(PoopCleaning.to_json()) +print(poop_cleaning_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -poop_cleaning_dict = poop_cleaning_instance.to_dict() +poop_cleaning_dict = poop_cleaning_instance.model_dump(by_alias=True) # create an instance of PoopCleaning from a dict -poop_cleaning_from_dict = PoopCleaning.from_dict(poop_cleaning_dict) +poop_cleaning_from_dict = PoopCleaning.model_validate(poop_cleaning_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/PrimitiveString.md b/samples/openapi3/client/petstore/python/docs/PrimitiveString.md index 85ceb632e167..a1a9a3dc81b6 100644 --- a/samples/openapi3/client/petstore/python/docs/PrimitiveString.md +++ b/samples/openapi3/client/petstore/python/docs/PrimitiveString.md @@ -15,14 +15,14 @@ from petstore_api.models.primitive_string import PrimitiveString # TODO update the JSON string below json = "{}" # create an instance of PrimitiveString from a JSON string -primitive_string_instance = PrimitiveString.from_json(json) +primitive_string_instance = PrimitiveString.model_validate_json(json) # print the JSON string representation of the object -print(PrimitiveString.to_json()) +print(primitive_string_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -primitive_string_dict = primitive_string_instance.to_dict() +primitive_string_dict = primitive_string_instance.model_dump(by_alias=True) # create an instance of PrimitiveString from a dict -primitive_string_from_dict = PrimitiveString.from_dict(primitive_string_dict) +primitive_string_from_dict = PrimitiveString.model_validate(primitive_string_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/PropertyMap.md b/samples/openapi3/client/petstore/python/docs/PropertyMap.md index a55a0e5c6f01..5fcda1f7803d 100644 --- a/samples/openapi3/client/petstore/python/docs/PropertyMap.md +++ b/samples/openapi3/client/petstore/python/docs/PropertyMap.md @@ -15,14 +15,14 @@ from petstore_api.models.property_map import PropertyMap # TODO update the JSON string below json = "{}" # create an instance of PropertyMap from a JSON string -property_map_instance = PropertyMap.from_json(json) +property_map_instance = PropertyMap.model_validate_json(json) # print the JSON string representation of the object -print(PropertyMap.to_json()) +print(property_map_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -property_map_dict = property_map_instance.to_dict() +property_map_dict = property_map_instance.model_dump(by_alias=True) # create an instance of PropertyMap from a dict -property_map_from_dict = PropertyMap.from_dict(property_map_dict) +property_map_from_dict = PropertyMap.model_validate(property_map_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/PropertyNameCollision.md b/samples/openapi3/client/petstore/python/docs/PropertyNameCollision.md index 40c233670dd0..a4a8405fe847 100644 --- a/samples/openapi3/client/petstore/python/docs/PropertyNameCollision.md +++ b/samples/openapi3/client/petstore/python/docs/PropertyNameCollision.md @@ -17,14 +17,14 @@ from petstore_api.models.property_name_collision import PropertyNameCollision # TODO update the JSON string below json = "{}" # create an instance of PropertyNameCollision from a JSON string -property_name_collision_instance = PropertyNameCollision.from_json(json) +property_name_collision_instance = PropertyNameCollision.model_validate_json(json) # print the JSON string representation of the object -print(PropertyNameCollision.to_json()) +print(property_name_collision_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -property_name_collision_dict = property_name_collision_instance.to_dict() +property_name_collision_dict = property_name_collision_instance.model_dump(by_alias=True) # create an instance of PropertyNameCollision from a dict -property_name_collision_from_dict = PropertyNameCollision.from_dict(property_name_collision_dict) +property_name_collision_from_dict = PropertyNameCollision.model_validate(property_name_collision_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md index 686ec5da41c9..e55fe102b673 100644 --- a/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md +++ b/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md @@ -16,14 +16,14 @@ from petstore_api.models.read_only_first import ReadOnlyFirst # TODO update the JSON string below json = "{}" # create an instance of ReadOnlyFirst from a JSON string -read_only_first_instance = ReadOnlyFirst.from_json(json) +read_only_first_instance = ReadOnlyFirst.model_validate_json(json) # print the JSON string representation of the object -print(ReadOnlyFirst.to_json()) +print(read_only_first_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -read_only_first_dict = read_only_first_instance.to_dict() +read_only_first_dict = read_only_first_instance.model_dump(by_alias=True) # create an instance of ReadOnlyFirst from a dict -read_only_first_from_dict = ReadOnlyFirst.from_dict(read_only_first_dict) +read_only_first_from_dict = ReadOnlyFirst.model_validate(read_only_first_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/SecondCircularAllOfRef.md b/samples/openapi3/client/petstore/python/docs/SecondCircularAllOfRef.md index 65ebdd4c7e1d..47fb4daf97a4 100644 --- a/samples/openapi3/client/petstore/python/docs/SecondCircularAllOfRef.md +++ b/samples/openapi3/client/petstore/python/docs/SecondCircularAllOfRef.md @@ -16,14 +16,14 @@ from petstore_api.models.second_circular_all_of_ref import SecondCircularAllOfRe # TODO update the JSON string below json = "{}" # create an instance of SecondCircularAllOfRef from a JSON string -second_circular_all_of_ref_instance = SecondCircularAllOfRef.from_json(json) +second_circular_all_of_ref_instance = SecondCircularAllOfRef.model_validate_json(json) # print the JSON string representation of the object -print(SecondCircularAllOfRef.to_json()) +print(second_circular_all_of_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -second_circular_all_of_ref_dict = second_circular_all_of_ref_instance.to_dict() +second_circular_all_of_ref_dict = second_circular_all_of_ref_instance.model_dump(by_alias=True) # create an instance of SecondCircularAllOfRef from a dict -second_circular_all_of_ref_from_dict = SecondCircularAllOfRef.from_dict(second_circular_all_of_ref_dict) +second_circular_all_of_ref_from_dict = SecondCircularAllOfRef.model_validate(second_circular_all_of_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/SecondRef.md b/samples/openapi3/client/petstore/python/docs/SecondRef.md index dfb1a0ac6db5..fa0b9f285e0c 100644 --- a/samples/openapi3/client/petstore/python/docs/SecondRef.md +++ b/samples/openapi3/client/petstore/python/docs/SecondRef.md @@ -16,14 +16,14 @@ from petstore_api.models.second_ref import SecondRef # TODO update the JSON string below json = "{}" # create an instance of SecondRef from a JSON string -second_ref_instance = SecondRef.from_json(json) +second_ref_instance = SecondRef.model_validate_json(json) # print the JSON string representation of the object -print(SecondRef.to_json()) +print(second_ref_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -second_ref_dict = second_ref_instance.to_dict() +second_ref_dict = second_ref_instance.model_dump(by_alias=True) # create an instance of SecondRef from a dict -second_ref_from_dict = SecondRef.from_dict(second_ref_dict) +second_ref_from_dict = SecondRef.model_validate(second_ref_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/SelfReferenceModel.md b/samples/openapi3/client/petstore/python/docs/SelfReferenceModel.md index 208cdac04b6f..af3c77d0524b 100644 --- a/samples/openapi3/client/petstore/python/docs/SelfReferenceModel.md +++ b/samples/openapi3/client/petstore/python/docs/SelfReferenceModel.md @@ -16,14 +16,14 @@ from petstore_api.models.self_reference_model import SelfReferenceModel # TODO update the JSON string below json = "{}" # create an instance of SelfReferenceModel from a JSON string -self_reference_model_instance = SelfReferenceModel.from_json(json) +self_reference_model_instance = SelfReferenceModel.model_validate_json(json) # print the JSON string representation of the object -print(SelfReferenceModel.to_json()) +print(self_reference_model_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -self_reference_model_dict = self_reference_model_instance.to_dict() +self_reference_model_dict = self_reference_model_instance.model_dump(by_alias=True) # create an instance of SelfReferenceModel from a dict -self_reference_model_from_dict = SelfReferenceModel.from_dict(self_reference_model_dict) +self_reference_model_from_dict = SelfReferenceModel.model_validate(self_reference_model_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python/docs/SpecialModelName.md index 35303f34efd2..589dbeb14b94 100644 --- a/samples/openapi3/client/petstore/python/docs/SpecialModelName.md +++ b/samples/openapi3/client/petstore/python/docs/SpecialModelName.md @@ -15,14 +15,14 @@ from petstore_api.models.special_model_name import SpecialModelName # TODO update the JSON string below json = "{}" # create an instance of SpecialModelName from a JSON string -special_model_name_instance = SpecialModelName.from_json(json) +special_model_name_instance = SpecialModelName.model_validate_json(json) # print the JSON string representation of the object -print(SpecialModelName.to_json()) +print(special_model_name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -special_model_name_dict = special_model_name_instance.to_dict() +special_model_name_dict = special_model_name_instance.model_dump(by_alias=True) # create an instance of SpecialModelName from a dict -special_model_name_from_dict = SpecialModelName.from_dict(special_model_name_dict) +special_model_name_from_dict = SpecialModelName.model_validate(special_model_name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/SpecialName.md b/samples/openapi3/client/petstore/python/docs/SpecialName.md index ccc550b16e33..19da9016451c 100644 --- a/samples/openapi3/client/petstore/python/docs/SpecialName.md +++ b/samples/openapi3/client/petstore/python/docs/SpecialName.md @@ -17,14 +17,14 @@ from petstore_api.models.special_name import SpecialName # TODO update the JSON string below json = "{}" # create an instance of SpecialName from a JSON string -special_name_instance = SpecialName.from_json(json) +special_name_instance = SpecialName.model_validate_json(json) # print the JSON string representation of the object -print(SpecialName.to_json()) +print(special_name_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -special_name_dict = special_name_instance.to_dict() +special_name_dict = special_name_instance.model_dump(by_alias=True) # create an instance of SpecialName from a dict -special_name_from_dict = SpecialName.from_dict(special_name_dict) +special_name_from_dict = SpecialName.model_validate(special_name_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Tag.md b/samples/openapi3/client/petstore/python/docs/Tag.md index 4106d9cfe5db..66339d14c875 100644 --- a/samples/openapi3/client/petstore/python/docs/Tag.md +++ b/samples/openapi3/client/petstore/python/docs/Tag.md @@ -16,14 +16,14 @@ from petstore_api.models.tag import Tag # TODO update the JSON string below json = "{}" # create an instance of Tag from a JSON string -tag_instance = Tag.from_json(json) +tag_instance = Tag.model_validate_json(json) # print the JSON string representation of the object -print(Tag.to_json()) +print(tag_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tag_dict = tag_instance.to_dict() +tag_dict = tag_instance.model_dump(by_alias=True) # create an instance of Tag from a dict -tag_from_dict = Tag.from_dict(tag_dict) +tag_from_dict = Tag.model_validate(tag_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Task.md b/samples/openapi3/client/petstore/python/docs/Task.md index 85fa2776a059..229ed6510a11 100644 --- a/samples/openapi3/client/petstore/python/docs/Task.md +++ b/samples/openapi3/client/petstore/python/docs/Task.md @@ -17,14 +17,14 @@ from petstore_api.models.task import Task # TODO update the JSON string below json = "{}" # create an instance of Task from a JSON string -task_instance = Task.from_json(json) +task_instance = Task.model_validate_json(json) # print the JSON string representation of the object -print(Task.to_json()) +print(task_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -task_dict = task_instance.to_dict() +task_dict = task_instance.model_dump(by_alias=True) # create an instance of Task from a dict -task_from_dict = Task.from_dict(task_dict) +task_from_dict = Task.model_validate(task_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/TaskActivity.md b/samples/openapi3/client/petstore/python/docs/TaskActivity.md index e905a477292d..c025d32ba436 100644 --- a/samples/openapi3/client/petstore/python/docs/TaskActivity.md +++ b/samples/openapi3/client/petstore/python/docs/TaskActivity.md @@ -17,14 +17,14 @@ from petstore_api.models.task_activity import TaskActivity # TODO update the JSON string below json = "{}" # create an instance of TaskActivity from a JSON string -task_activity_instance = TaskActivity.from_json(json) +task_activity_instance = TaskActivity.model_validate_json(json) # print the JSON string representation of the object -print(TaskActivity.to_json()) +print(task_activity_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -task_activity_dict = task_activity_instance.to_dict() +task_activity_dict = task_activity_instance.model_dump(by_alias=True) # create an instance of TaskActivity from a dict -task_activity_from_dict = TaskActivity.from_dict(task_activity_dict) +task_activity_from_dict = TaskActivity.model_validate(task_activity_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel400Response.md b/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel400Response.md index be416bbad0f7..fed06705b55b 100644 --- a/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel400Response.md +++ b/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel400Response.md @@ -15,14 +15,14 @@ from petstore_api.models.test_error_responses_with_model400_response import Test # TODO update the JSON string below json = "{}" # create an instance of TestErrorResponsesWithModel400Response from a JSON string -test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.from_json(json) +test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.model_validate_json(json) # print the JSON string representation of the object -print(TestErrorResponsesWithModel400Response.to_json()) +print(test_error_responses_with_model400_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.to_dict() +test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.model_dump(by_alias=True) # create an instance of TestErrorResponsesWithModel400Response from a dict -test_error_responses_with_model400_response_from_dict = TestErrorResponsesWithModel400Response.from_dict(test_error_responses_with_model400_response_dict) +test_error_responses_with_model400_response_from_dict = TestErrorResponsesWithModel400Response.model_validate(test_error_responses_with_model400_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel404Response.md b/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel404Response.md index 1c984f847bf1..8813e0792d22 100644 --- a/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel404Response.md +++ b/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel404Response.md @@ -15,14 +15,14 @@ from petstore_api.models.test_error_responses_with_model404_response import Test # TODO update the JSON string below json = "{}" # create an instance of TestErrorResponsesWithModel404Response from a JSON string -test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.from_json(json) +test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.model_validate_json(json) # print the JSON string representation of the object -print(TestErrorResponsesWithModel404Response.to_json()) +print(test_error_responses_with_model404_response_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.to_dict() +test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.model_dump(by_alias=True) # create an instance of TestErrorResponsesWithModel404Response from a dict -test_error_responses_with_model404_response_from_dict = TestErrorResponsesWithModel404Response.from_dict(test_error_responses_with_model404_response_dict) +test_error_responses_with_model404_response_from_dict = TestErrorResponsesWithModel404Response.model_validate(test_error_responses_with_model404_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/TestInlineFreeformAdditionalPropertiesRequest.md b/samples/openapi3/client/petstore/python/docs/TestInlineFreeformAdditionalPropertiesRequest.md index 511132d689be..870cd8850e6b 100644 --- a/samples/openapi3/client/petstore/python/docs/TestInlineFreeformAdditionalPropertiesRequest.md +++ b/samples/openapi3/client/petstore/python/docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -15,14 +15,14 @@ from petstore_api.models.test_inline_freeform_additional_properties_request impo # TODO update the JSON string below json = "{}" # create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string -test_inline_freeform_additional_properties_request_instance = TestInlineFreeformAdditionalPropertiesRequest.from_json(json) +test_inline_freeform_additional_properties_request_instance = TestInlineFreeformAdditionalPropertiesRequest.model_validate_json(json) # print the JSON string representation of the object -print(TestInlineFreeformAdditionalPropertiesRequest.to_json()) +print(test_inline_freeform_additional_properties_request_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_inline_freeform_additional_properties_request_dict = test_inline_freeform_additional_properties_request_instance.to_dict() +test_inline_freeform_additional_properties_request_dict = test_inline_freeform_additional_properties_request_instance.model_dump(by_alias=True) # create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict -test_inline_freeform_additional_properties_request_from_dict = TestInlineFreeformAdditionalPropertiesRequest.from_dict(test_inline_freeform_additional_properties_request_dict) +test_inline_freeform_additional_properties_request_from_dict = TestInlineFreeformAdditionalPropertiesRequest.model_validate(test_inline_freeform_additional_properties_request_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/TestModelWithEnumDefault.md b/samples/openapi3/client/petstore/python/docs/TestModelWithEnumDefault.md index 7d46e86deba4..1f63056fe0f1 100644 --- a/samples/openapi3/client/petstore/python/docs/TestModelWithEnumDefault.md +++ b/samples/openapi3/client/petstore/python/docs/TestModelWithEnumDefault.md @@ -19,14 +19,14 @@ from petstore_api.models.test_model_with_enum_default import TestModelWithEnumDe # TODO update the JSON string below json = "{}" # create an instance of TestModelWithEnumDefault from a JSON string -test_model_with_enum_default_instance = TestModelWithEnumDefault.from_json(json) +test_model_with_enum_default_instance = TestModelWithEnumDefault.model_validate_json(json) # print the JSON string representation of the object -print(TestModelWithEnumDefault.to_json()) +print(test_model_with_enum_default_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_model_with_enum_default_dict = test_model_with_enum_default_instance.to_dict() +test_model_with_enum_default_dict = test_model_with_enum_default_instance.model_dump(by_alias=True) # create an instance of TestModelWithEnumDefault from a dict -test_model_with_enum_default_from_dict = TestModelWithEnumDefault.from_dict(test_model_with_enum_default_dict) +test_model_with_enum_default_from_dict = TestModelWithEnumDefault.model_validate(test_model_with_enum_default_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/TestObjectForMultipartRequestsRequestMarker.md b/samples/openapi3/client/petstore/python/docs/TestObjectForMultipartRequestsRequestMarker.md index ff0ca9ee00ac..bb685d44835a 100644 --- a/samples/openapi3/client/petstore/python/docs/TestObjectForMultipartRequestsRequestMarker.md +++ b/samples/openapi3/client/petstore/python/docs/TestObjectForMultipartRequestsRequestMarker.md @@ -15,14 +15,14 @@ from petstore_api.models.test_object_for_multipart_requests_request_marker impor # TODO update the JSON string below json = "{}" # create an instance of TestObjectForMultipartRequestsRequestMarker from a JSON string -test_object_for_multipart_requests_request_marker_instance = TestObjectForMultipartRequestsRequestMarker.from_json(json) +test_object_for_multipart_requests_request_marker_instance = TestObjectForMultipartRequestsRequestMarker.model_validate_json(json) # print the JSON string representation of the object -print(TestObjectForMultipartRequestsRequestMarker.to_json()) +print(test_object_for_multipart_requests_request_marker_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -test_object_for_multipart_requests_request_marker_dict = test_object_for_multipart_requests_request_marker_instance.to_dict() +test_object_for_multipart_requests_request_marker_dict = test_object_for_multipart_requests_request_marker_instance.model_dump(by_alias=True) # create an instance of TestObjectForMultipartRequestsRequestMarker from a dict -test_object_for_multipart_requests_request_marker_from_dict = TestObjectForMultipartRequestsRequestMarker.from_dict(test_object_for_multipart_requests_request_marker_dict) +test_object_for_multipart_requests_request_marker_from_dict = TestObjectForMultipartRequestsRequestMarker.model_validate(test_object_for_multipart_requests_request_marker_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/Tiger.md b/samples/openapi3/client/petstore/python/docs/Tiger.md index f1cf2133f0f7..90c7d8770979 100644 --- a/samples/openapi3/client/petstore/python/docs/Tiger.md +++ b/samples/openapi3/client/petstore/python/docs/Tiger.md @@ -15,14 +15,14 @@ from petstore_api.models.tiger import Tiger # TODO update the JSON string below json = "{}" # create an instance of Tiger from a JSON string -tiger_instance = Tiger.from_json(json) +tiger_instance = Tiger.model_validate_json(json) # print the JSON string representation of the object -print(Tiger.to_json()) +print(tiger_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -tiger_dict = tiger_instance.to_dict() +tiger_dict = tiger_instance.model_dump(by_alias=True) # create an instance of Tiger from a dict -tiger_from_dict = Tiger.from_dict(tiger_dict) +tiger_from_dict = Tiger.model_validate(tiger_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalModelListProperties.md b/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalModelListProperties.md index 68cd00ab0a7a..0b411bf5df7b 100644 --- a/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalModelListProperties.md +++ b/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalModelListProperties.md @@ -15,14 +15,14 @@ from petstore_api.models.unnamed_dict_with_additional_model_list_properties impo # TODO update the JSON string below json = "{}" # create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string -unnamed_dict_with_additional_model_list_properties_instance = UnnamedDictWithAdditionalModelListProperties.from_json(json) +unnamed_dict_with_additional_model_list_properties_instance = UnnamedDictWithAdditionalModelListProperties.model_validate_json(json) # print the JSON string representation of the object -print(UnnamedDictWithAdditionalModelListProperties.to_json()) +print(unnamed_dict_with_additional_model_list_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -unnamed_dict_with_additional_model_list_properties_dict = unnamed_dict_with_additional_model_list_properties_instance.to_dict() +unnamed_dict_with_additional_model_list_properties_dict = unnamed_dict_with_additional_model_list_properties_instance.model_dump(by_alias=True) # create an instance of UnnamedDictWithAdditionalModelListProperties from a dict -unnamed_dict_with_additional_model_list_properties_from_dict = UnnamedDictWithAdditionalModelListProperties.from_dict(unnamed_dict_with_additional_model_list_properties_dict) +unnamed_dict_with_additional_model_list_properties_from_dict = UnnamedDictWithAdditionalModelListProperties.model_validate(unnamed_dict_with_additional_model_list_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalStringListProperties.md b/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalStringListProperties.md index 045b0e22ad09..def639720586 100644 --- a/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalStringListProperties.md +++ b/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalStringListProperties.md @@ -15,14 +15,14 @@ from petstore_api.models.unnamed_dict_with_additional_string_list_properties imp # TODO update the JSON string below json = "{}" # create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string -unnamed_dict_with_additional_string_list_properties_instance = UnnamedDictWithAdditionalStringListProperties.from_json(json) +unnamed_dict_with_additional_string_list_properties_instance = UnnamedDictWithAdditionalStringListProperties.model_validate_json(json) # print the JSON string representation of the object -print(UnnamedDictWithAdditionalStringListProperties.to_json()) +print(unnamed_dict_with_additional_string_list_properties_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -unnamed_dict_with_additional_string_list_properties_dict = unnamed_dict_with_additional_string_list_properties_instance.to_dict() +unnamed_dict_with_additional_string_list_properties_dict = unnamed_dict_with_additional_string_list_properties_instance.model_dump(by_alias=True) # create an instance of UnnamedDictWithAdditionalStringListProperties from a dict -unnamed_dict_with_additional_string_list_properties_from_dict = UnnamedDictWithAdditionalStringListProperties.from_dict(unnamed_dict_with_additional_string_list_properties_dict) +unnamed_dict_with_additional_string_list_properties_from_dict = UnnamedDictWithAdditionalStringListProperties.model_validate(unnamed_dict_with_additional_string_list_properties_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md index 141027780371..35be1642e660 100644 --- a/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md +++ b/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -16,14 +16,14 @@ from petstore_api.models.upload_file_with_additional_properties_request_object i # TODO update the JSON string below json = "{}" # create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string -upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.from_json(json) +upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.model_validate_json(json) # print the JSON string representation of the object -print(UploadFileWithAdditionalPropertiesRequestObject.to_json()) +print(upload_file_with_additional_properties_request_object_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.to_dict() +upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.model_dump(by_alias=True) # create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict -upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.from_dict(upload_file_with_additional_properties_request_object_dict) +upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.model_validate(upload_file_with_additional_properties_request_object_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/User.md b/samples/openapi3/client/petstore/python/docs/User.md index c45d26d27043..8f4ae3d04712 100644 --- a/samples/openapi3/client/petstore/python/docs/User.md +++ b/samples/openapi3/client/petstore/python/docs/User.md @@ -22,14 +22,14 @@ from petstore_api.models.user import User # TODO update the JSON string below json = "{}" # create an instance of User from a JSON string -user_instance = User.from_json(json) +user_instance = User.model_validate_json(json) # print the JSON string representation of the object -print(User.to_json()) +print(user_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -user_dict = user_instance.to_dict() +user_dict = user_instance.model_dump(by_alias=True) # create an instance of User from a dict -user_from_dict = User.from_dict(user_dict) +user_from_dict = User.model_validate(user_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/WithNestedOneOf.md b/samples/openapi3/client/petstore/python/docs/WithNestedOneOf.md index e7bbbc28fc2d..12d648bb920d 100644 --- a/samples/openapi3/client/petstore/python/docs/WithNestedOneOf.md +++ b/samples/openapi3/client/petstore/python/docs/WithNestedOneOf.md @@ -17,14 +17,14 @@ from petstore_api.models.with_nested_one_of import WithNestedOneOf # TODO update the JSON string below json = "{}" # create an instance of WithNestedOneOf from a JSON string -with_nested_one_of_instance = WithNestedOneOf.from_json(json) +with_nested_one_of_instance = WithNestedOneOf.model_validate_json(json) # print the JSON string representation of the object -print(WithNestedOneOf.to_json()) +print(with_nested_one_of_instance.model_dump_json(by_alias=True, exclude_unset=True)) # convert the object into a dict -with_nested_one_of_dict = with_nested_one_of_instance.to_dict() +with_nested_one_of_dict = with_nested_one_of_instance.model_dump(by_alias=True) # create an instance of WithNestedOneOf from a dict -with_nested_one_of_from_dict = WithNestedOneOf.from_dict(with_nested_one_of_dict) +with_nested_one_of_from_dict = WithNestedOneOf.model_validate(with_nested_one_of_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/petstore_api/api_client.py b/samples/openapi3/client/petstore/python/petstore_api/api_client.py index 1e2c74b334c8..666d00d5f216 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api_client.py @@ -714,7 +714,7 @@ def __deserialize_file(self, response): content_disposition ) assert m is not None, "Unexpected 'content-disposition' header value" - filename = m.group(1) + filename = os.path.basename(m.group(1)) # Strip any directory traversal path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py index 291b5e55e353..d3c2e0c15c8d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesAnyType(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesAnyType(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesAnyType from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesAnyType from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_class.py index 220f23a423b4..98a41160b3b2 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_class.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesClass(BaseModel): """ @@ -38,65 +39,27 @@ class AdditionalPropertiesClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "map_property": obj.get("map_property"), - "map_of_map_property": obj.get("map_of_map_property") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py index 00707c3c4818..4484e38c8bef 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesObject(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py index d8049b519ed0..0dd3de45f5d3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AdditionalPropertiesWithDescriptionOnly(BaseModel): """ @@ -37,64 +38,27 @@ class AdditionalPropertiesWithDescriptionOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AdditionalPropertiesWithDescriptionOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/all_of_super_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/all_of_super_model.py index b63bba1206a2..fb0462733d3b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/all_of_super_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/all_of_super_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AllOfSuperModel(BaseModel): """ @@ -37,64 +38,27 @@ class AllOfSuperModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AllOfSuperModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AllOfSuperModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/all_of_with_single_ref.py b/samples/openapi3/client/petstore/python/petstore_api/models/all_of_with_single_ref.py index e3fa084b0709..41022273145a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/all_of_with_single_ref.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/all_of_with_single_ref.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.single_ref_type import SingleRefType from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class AllOfWithSingleRef(BaseModel): """ @@ -39,65 +40,27 @@ class AllOfWithSingleRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of AllOfWithSingleRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of AllOfWithSingleRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "username": obj.get("username"), - "SingleRefType": obj.get("SingleRefType") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/animal.py b/samples/openapi3/client/petstore/python/petstore_api/models/animal.py index 131ad8d0ed60..9a785d57c411 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/animal.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -61,59 +62,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[Cat, Dog]]: - """Create an instance of Animal from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[Cat, Dog]]: - """Create an instance of Animal from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'Cat': - return import_module("petstore_api.models.cat").Cat.from_dict(obj) - if object_type == 'Dog': - return import_module("petstore_api.models.dog").Dog.from_dict(obj) - - raise ValueError("Animal failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py index f6d277e79498..b86b03be3591 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py @@ -13,8 +13,6 @@ from __future__ import annotations -from inspect import getfullargspec -import json import pprint import re # noqa: F401 from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator @@ -22,135 +20,56 @@ from typing_extensions import Annotated from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self -from pydantic import Field +from pydantic import Field, RootModel ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] -class AnyOfColor(BaseModel): + +class AnyOfColor(RootModel[Union[List[int], str]]): """ Any of RGB array, RGBA array, or hex string. """ - # data type: List[int] - anyof_schema_1_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=3, max_length=3)]] = Field(default=None, description="RGB three element array with values 0-255.") - # data type: List[int] - anyof_schema_2_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=4, max_length=4)]] = Field(default=None, description="RGBA four element array with values 0-255.") - # data type: str - anyof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") - if TYPE_CHECKING: - actual_instance: Optional[Union[List[int], str]] = None - else: - actual_instance: Any = None - any_of_schemas: Set[str] = { "List[int]", "str" } - - model_config = { - "validate_assignment": True, - "protected_namespaces": (), - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - instance = AnyOfColor.model_construct() - error_messages = [] - # validate data type: List[int] - try: - instance.anyof_schema_1_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: List[int] - try: - instance.anyof_schema_2_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.anyof_schema_3_validator = v - return v - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return v + root: Union[List[int], str] = Field( + ... + ) + + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ + + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod def from_dict(cls, obj: Dict[str, Any]) -> Self: - return cls.from_json(json.dumps(obj)) + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - # deserialize data into List[int] - try: - # validation - instance.anyof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_1_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into List[int] - try: - # validation - instance.anyof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_2_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.anyof_schema_3_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.anyof_schema_3_validator - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into AnyOfColor with anyOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) + return self.model_dump_json(by_alias=True, exclude_none=True) - def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py index c949e136f415..a632d3c382d6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py @@ -13,8 +13,6 @@ from __future__ import annotations -from inspect import getfullargspec -import json import pprint import re # noqa: F401 from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator @@ -23,112 +21,56 @@ from petstore_api.models.danish_pig import DanishPig from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict from typing_extensions import Literal, Self -from pydantic import Field +from pydantic import Field, RootModel ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] -class AnyOfPig(BaseModel): + +class AnyOfPig(RootModel[Union[BasquePig, DanishPig]]): """ AnyOfPig """ - # data type: BasquePig - anyof_schema_1_validator: Optional[BasquePig] = None - # data type: DanishPig - anyof_schema_2_validator: Optional[DanishPig] = None - if TYPE_CHECKING: - actual_instance: Optional[Union[BasquePig, DanishPig]] = None - else: - actual_instance: Any = None - any_of_schemas: Set[str] = { "BasquePig", "DanishPig" } - - model_config = { - "validate_assignment": True, - "protected_namespaces": (), - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_anyof(cls, v): - instance = AnyOfPig.model_construct() - error_messages = [] - # validate data type: BasquePig - if not isinstance(v, BasquePig): - error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`") - else: - return v - - # validate data type: DanishPig - if not isinstance(v, DanishPig): - error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`") - else: - return v - - if error_messages: - # no match - raise ValueError("No match found when setting the actual_instance in AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return v + root: Union[BasquePig, DanishPig] = Field( + ... + ) + + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ + + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod def from_dict(cls, obj: Dict[str, Any]) -> Self: - return cls.from_json(json.dumps(obj)) + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - # anyof_schema_1_validator: Optional[BasquePig] = None - try: - instance.actual_instance = BasquePig.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # anyof_schema_2_validator: Optional[DanishPig] = None - try: - instance.actual_instance = DanishPig.from_json(json_str) - return instance - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if error_messages: - # no match - raise ValueError("No match found when deserializing the JSON string into AnyOfPig with anyOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" - - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) + return self.model_dump_json(by_alias=True, exclude_none=True) - def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_model.py index 80d4aa689164..17afbb8e1cb5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_model.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfArrayOfModel(BaseModel): """ @@ -38,76 +39,27 @@ class ArrayOfArrayOfModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in another_property (list of list) - _items = [] - if self.another_property: - for _item_another_property in self.another_property: - if _item_another_property: - _items.append( - [_inner_item.to_dict() for _inner_item in _item_another_property if _inner_item is not None] - ) - _dict['another_property'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "another_property": [ - [Tag.from_dict(_inner_item) for _inner_item in _item] - for _item in obj["another_property"] - ] if obj.get("another_property") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py index 847ae88c4ffa..c3d9327871dc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictFloat from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfArrayOfNumberOnly(BaseModel): """ @@ -37,64 +38,27 @@ class ArrayOfArrayOfNumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfNumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfArrayOfNumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "ArrayArrayNumber": obj.get("ArrayArrayNumber") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_number_only.py index 4634914c33eb..7fdbf469baba 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictFloat from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayOfNumberOnly(BaseModel): """ @@ -37,64 +38,27 @@ class ArrayOfNumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayOfNumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayOfNumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "ArrayNumber": obj.get("ArrayNumber") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/array_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/array_test.py index 9cadd4e7beb7..277694149dd2 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/array_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/array_test.py @@ -22,7 +22,8 @@ from typing_extensions import Annotated from petstore_api.models.read_only_first import ReadOnlyFirst from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ArrayTest(BaseModel): """ @@ -42,79 +43,27 @@ class ArrayTest(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ArrayTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in array_array_of_model (list of list) - _items = [] - if self.array_array_of_model: - for _item_array_array_of_model in self.array_array_of_model: - if _item_array_array_of_model: - _items.append( - [_inner_item.to_dict() for _inner_item in _item_array_array_of_model if _inner_item is not None] - ) - _dict['array_array_of_model'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ArrayTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "array_of_string": obj.get("array_of_string"), - "array_of_nullable_float": obj.get("array_of_nullable_float"), - "array_array_of_integer": obj.get("array_array_of_integer"), - "array_array_of_model": [ - [ReadOnlyFirst.from_dict(_inner_item) for _inner_item in _item] - for _item in obj["array_array_of_model"] - ] if obj.get("array_array_of_model") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/base_discriminator.py b/samples/openapi3/client/petstore/python/petstore_api/models/base_discriminator.py index 40b49a2fca7f..c7853a6c9be8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/base_discriminator.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/base_discriminator.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -60,59 +61,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[PrimitiveString, Info]]: - """Create an instance of BaseDiscriminator from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[PrimitiveString, Info]]: - """Create an instance of BaseDiscriminator from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'PrimitiveString': - return import_module("petstore_api.models.primitive_string").PrimitiveString.from_dict(obj) - if object_type == 'Info': - return import_module("petstore_api.models.info").Info.from_dict(obj) - - raise ValueError("BaseDiscriminator failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/basque_pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/basque_pig.py index 4a5b9e3bcb9d..f88eb2e92af0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/basque_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/basque_pig.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class BasquePig(BaseModel): """ @@ -38,65 +39,27 @@ class BasquePig(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of BasquePig from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of BasquePig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/bathing.py b/samples/openapi3/client/petstore/python/petstore_api/models/bathing.py index 289d9d4670ab..bac0c4a55e6b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/bathing.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/bathing.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Bathing(BaseModel): """ Bathing """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning_deep'] = Field( + ..., + description="task_name of the Bathing", + alias="task_name" + ) + function_name: Literal['care_nourish'] = Field( + ..., + description="function_name of the Bathing", + alias="function_name" + ) content: StrictStr additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -53,66 +62,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Bathing from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Bathing from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/capitalization.py b/samples/openapi3/client/petstore/python/petstore_api/models/capitalization.py index d98aa21e532d..47eaa639b7f7 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/capitalization.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/capitalization.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Capitalization(BaseModel): """ @@ -42,69 +43,27 @@ class Capitalization(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Capitalization from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Capitalization from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "smallCamel": obj.get("smallCamel"), - "CapitalCamel": obj.get("CapitalCamel"), - "small_Snake": obj.get("small_Snake"), - "Capital_Snake": obj.get("Capital_Snake"), - "SCA_ETH_Flow_Points": obj.get("SCA_ETH_Flow_Points"), - "ATT_NAME": obj.get("ATT_NAME") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/cat.py b/samples/openapi3/client/petstore/python/petstore_api/models/cat.py index 86002178c904..a982c0e5048d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/cat.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Cat(Animal): """ @@ -38,66 +39,27 @@ class Cat(Animal): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Cat from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Cat from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") if obj.get("color") is not None else 'red', - "declawed": obj.get("declawed") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/category.py b/samples/openapi3/client/petstore/python/petstore_api/models/category.py index c659f1845726..9d872fde9d05 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/category.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/category.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Category(BaseModel): """ @@ -38,65 +39,27 @@ class Category(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Category from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Category from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") if obj.get("name") is not None else 'default-name' - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/circular_all_of_ref.py b/samples/openapi3/client/petstore/python/petstore_api/models/circular_all_of_ref.py index d3b6cbe57ea1..cc547e3c1122 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/circular_all_of_ref.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/circular_all_of_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CircularAllOfRef(BaseModel): """ @@ -38,73 +39,28 @@ class CircularAllOfRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CircularAllOfRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in second_circular_all_of_ref (list) - _items = [] - if self.second_circular_all_of_ref: - for _item_second_circular_all_of_ref in self.second_circular_all_of_ref: - if _item_second_circular_all_of_ref: - _items.append(_item_second_circular_all_of_ref.to_dict()) - _dict['secondCircularAllOfRef'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CircularAllOfRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name"), - "secondCircularAllOfRef": [SecondCircularAllOfRef.from_dict(_item) for _item in obj["secondCircularAllOfRef"]] if obj.get("secondCircularAllOfRef") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.second_circular_all_of_ref import SecondCircularAllOfRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/circular_reference_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/circular_reference_model.py index 8c118f3c09b2..7524f9ee4b71 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/circular_reference_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/circular_reference_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CircularReferenceModel(BaseModel): """ @@ -38,69 +39,28 @@ class CircularReferenceModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CircularReferenceModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested - if self.nested: - _dict['nested'] = self.nested.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CircularReferenceModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested": FirstRef.from_dict(obj["nested"]) if obj.get("nested") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.first_ref import FirstRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/class_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/class_model.py index 06f8f91b83cb..24e5f75ac3f1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/class_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/class_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ClassModel(BaseModel): """ @@ -37,64 +38,27 @@ class ClassModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ClassModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ClassModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_class": obj.get("_class") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/client.py b/samples/openapi3/client/petstore/python/petstore_api/models/client.py index d3376d62357b..fb089635fd0a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/client.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Client(BaseModel): """ @@ -37,64 +38,27 @@ class Client(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Client from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Client from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "client": obj.get("client") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/color.py b/samples/openapi3/client/petstore/python/petstore_api/models/color.py index bb740fb597d4..5197fe58ecc6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/color.py @@ -18,150 +18,55 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional from typing_extensions import Annotated -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] -class Color(BaseModel): +class Color(RootModel[Union[List[int], str]]): """ RGB array, RGBA array, or hex string. """ - # data type: List[int] - oneof_schema_1_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=3, max_length=3)]] = Field(default=None, description="RGB three element array with values 0-255.") - # data type: List[int] - oneof_schema_2_validator: Optional[Annotated[List[Annotated[int, Field(le=255, strict=True, ge=0)]], Field(min_length=4, max_length=4)]] = Field(default=None, description="RGBA four element array with values 0-255.") - # data type: str - oneof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") - actual_instance: Optional[Union[List[int], str]] = None - one_of_schemas: Set[str] = { "List[int]", "str" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[List[int], str, None] = Field( + None ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - if v is None: - return v - - instance = Color.model_construct() - error_messages = [] - match = 0 - # validate data type: List[int] - try: - instance.oneof_schema_1_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: List[int] - try: - instance.oneof_schema_2_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.oneof_schema_3_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: Optional[str]) -> Self: + def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - if json_str is None: - return instance - - error_messages = [] - match = 0 - - # deserialize data into List[int] - try: - # validation - instance.oneof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_1_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into List[int] - try: - # validation - instance.oneof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_2_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.oneof_schema_3_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_3_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into Color with oneOf schemas: List[int], str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/creature.py b/samples/openapi3/client/petstore/python/petstore_api/models/creature.py index ce6a70327b1a..06debc61d646 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/creature.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/creature.py @@ -22,7 +22,8 @@ from typing import Any, ClassVar, Dict, List, Union from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -61,60 +62,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[HuntingDog]]: - """Create an instance of Creature from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of info - if self.info: - _dict['info'] = self.info.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[HuntingDog]]: - """Create an instance of Creature from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'HuntingDog': - return import_module("petstore_api.models.hunting_dog").HuntingDog.from_dict(obj) - - raise ValueError("Creature failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/creature_info.py b/samples/openapi3/client/petstore/python/petstore_api/models/creature_info.py index e7fef158a580..d7b41b7b9580 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/creature_info.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/creature_info.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class CreatureInfo(BaseModel): """ @@ -37,64 +38,27 @@ class CreatureInfo(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of CreatureInfo from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of CreatureInfo from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/danish_pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/danish_pig.py index df4a80d33908..3fb64cdaf2c8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/danish_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/danish_pig.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DanishPig(BaseModel): """ @@ -38,65 +39,27 @@ class DanishPig(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DanishPig from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DanishPig from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "size": obj.get("size") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/deprecated_object.py b/samples/openapi3/client/petstore/python/petstore_api/models/deprecated_object.py index ad0ec89a5b7a..2194c3231637 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/deprecated_object.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/deprecated_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DeprecatedObject(BaseModel): """ @@ -37,64 +38,27 @@ class DeprecatedObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DeprecatedObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DeprecatedObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/discriminator_all_of_sub.py b/samples/openapi3/client/petstore/python/petstore_api/models/discriminator_all_of_sub.py index 9723d2e28c74..f2a1fdfe4a61 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/discriminator_all_of_sub.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/discriminator_all_of_sub.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List from petstore_api.models.discriminator_all_of_super import DiscriminatorAllOfSuper from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DiscriminatorAllOfSub(DiscriminatorAllOfSuper): """ @@ -37,64 +38,27 @@ class DiscriminatorAllOfSub(DiscriminatorAllOfSuper): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DiscriminatorAllOfSub from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DiscriminatorAllOfSub from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "elementType": obj.get("elementType") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/discriminator_all_of_super.py b/samples/openapi3/client/petstore/python/petstore_api/models/discriminator_all_of_super.py index e3d62831065a..ec0647d296c4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/discriminator_all_of_super.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/discriminator_all_of_super.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Union from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field from typing import TYPE_CHECKING if TYPE_CHECKING: @@ -59,57 +60,27 @@ def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: else: return None - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Union[DiscriminatorAllOfSub]]: - """Create an instance of DiscriminatorAllOfSuper from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[DiscriminatorAllOfSub]]: - """Create an instance of DiscriminatorAllOfSuper from a dict""" - # look up the object type based on discriminator mapping - object_type = cls.get_discriminator_value(obj) - if object_type == 'DiscriminatorAllOfSub': - return import_module("petstore_api.models.discriminator_all_of_sub").DiscriminatorAllOfSub.from_dict(obj) - - raise ValueError("DiscriminatorAllOfSuper failed to lookup discriminator value from " + - json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + - ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/dog.py b/samples/openapi3/client/petstore/python/petstore_api/models/dog.py index cde0f5d27e0c..de660986c36c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/dog.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/dog.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Dog(Animal): """ @@ -38,66 +39,27 @@ class Dog(Animal): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Dog from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Dog from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "className": obj.get("className"), - "color": obj.get("color") if obj.get("color") is not None else 'red', - "breed": obj.get("breed") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/dummy_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/dummy_model.py index 47fdb81a397a..6eaf6cd615de 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/dummy_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/dummy_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class DummyModel(BaseModel): """ @@ -38,69 +39,28 @@ class DummyModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of DummyModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of self_ref - if self.self_ref: - _dict['self_ref'] = self.self_ref.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of DummyModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "self_ref": SelfReferenceModel.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.self_reference_model import SelfReferenceModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py index 17d3e0afd2df..315c4c93abce 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py @@ -20,14 +20,21 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumArrays(BaseModel): """ EnumArrays """ # noqa: E501 - just_symbol: Optional[StrictStr] = None - array_enum: Optional[List[StrictStr]] = None + just_symbol: Optional[Literal['>=', '$']] = Field( + None, + description="just_symbol of the EnumArrays" + ) + array_enum: Optional[List[Literal['fish', 'crab']]] = Field( + None, + description="array_enum of the EnumArrays" + ) additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["just_symbol", "array_enum"] @@ -59,65 +66,27 @@ def array_enum_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumArrays from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumArrays from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "just_symbol": obj.get("just_symbol"), - "array_enum": obj.get("array_enum") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/enum_ref_with_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_ref_with_default_value.py index d864e80d0a73..d697019cf974 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_ref_with_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_ref_with_default_value.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.data_output_format import DataOutputFormat from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumRefWithDefaultValue(BaseModel): """ @@ -38,64 +39,27 @@ class EnumRefWithDefaultValue(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumRefWithDefaultValue from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumRefWithDefaultValue from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "report_format": obj.get("report_format") if obj.get("report_format") is not None else DataOutputFormat.JSON - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py index d39c2c95775e..d273604b81bc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py @@ -26,19 +26,43 @@ from petstore_api.models.outer_enum_integer import OuterEnumInteger from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class EnumTest(BaseModel): """ EnumTest """ # noqa: E501 - enum_string: Optional[StrictStr] = None - enum_string_required: StrictStr - enum_integer_default: Optional[StrictInt] = 5 - enum_integer: Optional[StrictInt] = None - enum_number: Optional[StrictFloat] = None - enum_string_single_member: Optional[StrictStr] = None - enum_integer_single_member: Optional[StrictInt] = None + enum_string: Optional[Literal['UPPER', 'lower', '']] = Field( + None, + description="enum_string of the EnumTest" + ) + enum_string_required: Literal['UPPER', 'lower', ''] = Field( + ..., + description="enum_string_required of the EnumTest" + ) + enum_integer_default: Optional[Literal[1, 5, 14]] = Field( + None, + description="enum_integer_default of the EnumTest" + ) + enum_integer: Optional[Literal[1, -1]] = Field( + None, + description="enum_integer of the EnumTest" + ) + enum_number: Optional[Literal[1.1, -1.2]] = Field( + None, + description="enum_number of the EnumTest" + ) + enum_string_single_member: Literal['abc'] = Field( + None, + description="enum_string_single_member of the EnumTest", + alias="enum_string_single_member" + ) + enum_integer_single_member: Literal['100'] = Field( + None, + description="enum_integer_single_member of the EnumTest", + alias="enum_integer_single_member" + ) outer_enum: Optional[OuterEnum] = Field(default=None, alias="outerEnum") outer_enum_integer: Optional[OuterEnumInteger] = Field(default=None, alias="outerEnumInteger") outer_enum_default_value: Optional[OuterEnumDefaultValue] = Field(default=OuterEnumDefaultValue.PLACED, alias="outerEnumDefaultValue") @@ -122,81 +146,27 @@ def enum_integer_single_member_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of EnumTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if outer_enum (nullable) is None - # and model_fields_set contains the field - if self.outer_enum is None and "outer_enum" in self.model_fields_set: - _dict['outerEnum'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of EnumTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "enum_string": obj.get("enum_string"), - "enum_string_required": obj.get("enum_string_required"), - "enum_integer_default": obj.get("enum_integer_default") if obj.get("enum_integer_default") is not None else 5, - "enum_integer": obj.get("enum_integer"), - "enum_number": obj.get("enum_number"), - "enum_string_single_member": obj.get("enum_string_single_member"), - "enum_integer_single_member": obj.get("enum_integer_single_member"), - "outerEnum": obj.get("outerEnum"), - "outerEnumInteger": obj.get("outerEnumInteger"), - "outerEnumDefaultValue": obj.get("outerEnumDefaultValue") if obj.get("outerEnumDefaultValue") is not None else OuterEnumDefaultValue.PLACED, - "outerEnumIntegerDefaultValue": obj.get("outerEnumIntegerDefaultValue") if obj.get("outerEnumIntegerDefaultValue") is not None else OuterEnumIntegerDefaultValue.NUMBER_0, - "enumNumberVendorExt": obj.get("enumNumberVendorExt"), - "enumStringVendorExt": obj.get("enumStringVendorExt") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/feeding.py b/samples/openapi3/client/petstore/python/petstore_api/models/feeding.py index 5c406bc9e65e..3137d25e1585 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/feeding.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/feeding.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Feeding(BaseModel): """ Feeding """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning'] = Field( + ..., + description="task_name of the Feeding", + alias="task_name" + ) + function_name: Literal['care_nourish'] = Field( + ..., + description="function_name of the Feeding", + alias="function_name" + ) content: StrictStr additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -53,66 +62,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Feeding from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Feeding from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/file.py b/samples/openapi3/client/petstore/python/petstore_api/models/file.py index 4c661cadabc4..c5b12aa2a78e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/file.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/file.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class File(BaseModel): """ @@ -37,64 +38,27 @@ class File(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of File from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of File from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "sourceURI": obj.get("sourceURI") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/file_schema_test_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/file_schema_test_class.py index 09a543010f4d..127507d62b47 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/file_schema_test_class.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.file import File from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FileSchemaTestClass(BaseModel): """ @@ -39,75 +40,27 @@ class FileSchemaTestClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FileSchemaTestClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of file - if self.file: - _dict['file'] = self.file.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in files (list) - _items = [] - if self.files: - for _item_files in self.files: - if _item_files: - _items.append(_item_files.to_dict()) - _dict['files'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FileSchemaTestClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "file": File.from_dict(obj["file"]) if obj.get("file") is not None else None, - "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/first_ref.py b/samples/openapi3/client/petstore/python/petstore_api/models/first_ref.py index 7680dfdf418c..e98d1438f4d9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/first_ref.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/first_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FirstRef(BaseModel): """ @@ -38,69 +39,28 @@ class FirstRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FirstRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of self_ref - if self.self_ref: - _dict['self_ref'] = self.self_ref.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FirstRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "self_ref": SecondRef.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.second_ref import SecondRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/foo.py b/samples/openapi3/client/petstore/python/petstore_api/models/foo.py index 81e3839ea17c..f29f366bb7d9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/foo.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/foo.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Foo(BaseModel): """ @@ -37,64 +38,27 @@ class Foo(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Foo from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Foo from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar") if obj.get("bar") is not None else 'bar' - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/foo_get_default_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/foo_get_default_response.py index 4cd23db39125..63f2dc274345 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/foo_get_default_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/foo_get_default_response.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.foo import Foo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FooGetDefaultResponse(BaseModel): """ @@ -38,67 +39,27 @@ class FooGetDefaultResponse(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FooGetDefaultResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of string - if self.string: - _dict['string'] = self.string.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FooGetDefaultResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "string": Foo.from_dict(obj["string"]) if obj.get("string") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/format_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/format_test.py index 4aca97f91c48..8f7df0d352bc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/format_test.py @@ -24,7 +24,8 @@ from typing_extensions import Annotated from uuid import UUID from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class FormatTest(BaseModel): """ @@ -97,80 +98,27 @@ def pattern_with_digits_and_delimiter_validate_regular_expression(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of FormatTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of FormatTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "integer": obj.get("integer"), - "int32": obj.get("int32"), - "int64": obj.get("int64"), - "number": obj.get("number"), - "float": obj.get("float"), - "double": obj.get("double"), - "decimal": obj.get("decimal"), - "string": obj.get("string"), - "string_with_double_quote_pattern": obj.get("string_with_double_quote_pattern"), - "byte": obj.get("byte"), - "binary": obj.get("binary"), - "date": obj.get("date"), - "dateTime": obj.get("dateTime"), - "uuid": obj.get("uuid"), - "password": obj.get("password"), - "pattern_with_digits": obj.get("pattern_with_digits"), - "pattern_with_digits_and_delimiter": obj.get("pattern_with_digits_and_delimiter") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/has_only_read_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/has_only_read_only.py index 77360fedbae5..a8a2b326c9c8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/has_only_read_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HasOnlyReadOnly(BaseModel): """ @@ -38,69 +39,27 @@ class HasOnlyReadOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HasOnlyReadOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * OpenAPI `readOnly` fields are excluded. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "bar", - "foo", - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HasOnlyReadOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar"), - "foo": obj.get("foo") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/health_check_result.py b/samples/openapi3/client/petstore/python/petstore_api/models/health_check_result.py index 59f444aedaa3..675586246101 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/health_check_result.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/health_check_result.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HealthCheckResult(BaseModel): """ @@ -37,69 +38,27 @@ class HealthCheckResult(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HealthCheckResult from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if nullable_message (nullable) is None - # and model_fields_set contains the field - if self.nullable_message is None and "nullable_message" in self.model_fields_set: - _dict['NullableMessage'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HealthCheckResult from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "NullableMessage": obj.get("NullableMessage") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/hunting_dog.py b/samples/openapi3/client/petstore/python/petstore_api/models/hunting_dog.py index f7d03f4044ea..b11e6efcc967 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/hunting_dog.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/hunting_dog.py @@ -22,7 +22,8 @@ from petstore_api.models.creature import Creature from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class HuntingDog(Creature): """ @@ -39,69 +40,27 @@ class HuntingDog(Creature): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of HuntingDog from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of info - if self.info: - _dict['info'] = self.info.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of HuntingDog from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "info": CreatureInfo.from_dict(obj["info"]) if obj.get("info") is not None else None, - "type": obj.get("type"), - "isTrained": obj.get("isTrained") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/info.py b/samples/openapi3/client/petstore/python/petstore_api/models/info.py index 94e663b3aaab..72dc4b91cc79 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/info.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/info.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.base_discriminator import BaseDiscriminator from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Info(BaseDiscriminator): """ @@ -38,68 +39,27 @@ class Info(BaseDiscriminator): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Info from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of val - if self.val: - _dict['val'] = self.val.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Info from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_typeName": obj.get("_typeName"), - "val": BaseDiscriminator.from_dict(obj["val"]) if obj.get("val") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/inner_dict_with_property.py b/samples/openapi3/client/petstore/python/petstore_api/models/inner_dict_with_property.py index b43fa8b19fef..e03392c2d116 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/inner_dict_with_property.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/inner_dict_with_property.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class InnerDictWithProperty(BaseModel): """ @@ -37,64 +38,27 @@ class InnerDictWithProperty(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of InnerDictWithProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of InnerDictWithProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "aProperty": obj.get("aProperty") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/input_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/models/input_all_of.py index e4a81ff70006..661614b399a8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/input_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/input_all_of.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class InputAllOf(BaseModel): """ @@ -38,76 +39,27 @@ class InputAllOf(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of InputAllOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in some_data (dict) - _field_dict = {} - if self.some_data: - for _key_some_data in self.some_data: - if self.some_data[_key_some_data]: - _field_dict[_key_some_data] = self.some_data[_key_some_data].to_dict() - _dict['some_data'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of InputAllOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "some_data": dict( - (_k, Tag.from_dict(_v)) - for _k, _v in obj["some_data"].items() - ) - if obj.get("some_data") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py index f2a5a0a2d4a3..c66bf1ab9772 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py @@ -18,127 +18,55 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator from typing import Any, List, Optional from typing_extensions import Annotated -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] -class IntOrString(BaseModel): +class IntOrString(RootModel[Union[int, str]]): """ IntOrString """ - # data type: int - oneof_schema_1_validator: Optional[Annotated[int, Field(strict=True, ge=10)]] = None - # data type: str - oneof_schema_2_validator: Optional[StrictStr] = None - actual_instance: Optional[Union[int, str]] = None - one_of_schemas: Set[str] = { "int", "str" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[int, str] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = IntOrString.model_construct() - error_messages = [] - match = 0 - # validate data type: int - try: - instance.oneof_schema_1_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # validate data type: str - try: - instance.oneof_schema_2_validator = v - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into int - try: - # validation - instance.oneof_schema_1_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_1_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into str - try: - # validation - instance.oneof_schema_2_validator = json.loads(json_str) - # assign value to actual_instance - instance.actual_instance = instance.oneof_schema_2_validator - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into IntOrString with oneOf schemas: int, str. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/list_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/list_class.py index e00f3d820b88..4ea7c927440d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/list_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/list_class.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ListClass(BaseModel): """ @@ -37,64 +38,27 @@ class ListClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ListClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ListClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "123-list": obj.get("123-list") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/map_of_array_of_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/map_of_array_of_model.py index 68816ab29531..80a114e74c7a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/map_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/map_of_array_of_model.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MapOfArrayOfModel(BaseModel): """ @@ -38,80 +39,27 @@ class MapOfArrayOfModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MapOfArrayOfModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in shop_id_to_org_online_lip_map (dict of array) - _field_dict_of_array = {} - if self.shop_id_to_org_online_lip_map: - for _key_shop_id_to_org_online_lip_map in self.shop_id_to_org_online_lip_map: - if self.shop_id_to_org_online_lip_map[_key_shop_id_to_org_online_lip_map] is not None: - _field_dict_of_array[_key_shop_id_to_org_online_lip_map] = [ - _item.to_dict() for _item in self.shop_id_to_org_online_lip_map[_key_shop_id_to_org_online_lip_map] - ] - _dict['shopIdToOrgOnlineLipMap'] = _field_dict_of_array - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MapOfArrayOfModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "shopIdToOrgOnlineLipMap": dict( - (_k, - [Tag.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("shopIdToOrgOnlineLipMap", {}).items() - ) - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py index 4cefd36427f9..845b08e0a068 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py @@ -20,14 +20,18 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MapTest(BaseModel): """ MapTest """ # noqa: E501 map_map_of_string: Optional[Dict[str, Dict[str, StrictStr]]] = None - map_of_enum_string: Optional[Dict[str, StrictStr]] = None + map_of_enum_string: Optional[Literal['UPPER', 'lower']] = Field( + None, + description="map_of_enum_string of the MapTest" + ) direct_map: Optional[Dict[str, StrictBool]] = None indirect_map: Optional[Dict[str, StrictBool]] = None additional_properties: Dict[str, Any] = {} @@ -51,67 +55,27 @@ def map_of_enum_string_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MapTest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MapTest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "map_map_of_string": obj.get("map_map_of_string"), - "map_of_enum_string": obj.get("map_of_enum_string"), - "direct_map": obj.get("direct_map"), - "indirect_map": obj.get("indirect_map") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py index c21f442bb798..a8d7a0b8161a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -23,7 +23,8 @@ from uuid import UUID from petstore_api.models.animal import Animal from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): """ @@ -42,78 +43,27 @@ class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in map (dict) - _field_dict = {} - if self.map: - for _key_map in self.map: - if self.map[_key_map]: - _field_dict[_key_map] = self.map[_key_map].to_dict() - _dict['map'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "uuid": obj.get("uuid"), - "dateTime": obj.get("dateTime"), - "map": dict( - (_k, Animal.from_dict(_v)) - for _k, _v in obj["map"].items() - ) - if obj.get("map") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/model200_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/model200_response.py index 60e43a0e28e6..aee3b7e0020d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/model200_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/model200_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Model200Response(BaseModel): """ @@ -38,65 +39,27 @@ class Model200Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Model200Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Model200Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name"), - "class": obj.get("class") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/model_api_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/model_api_response.py index 7141160c57d9..a750ecd6c9c9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/model_api_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/model_api_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelApiResponse(BaseModel): """ @@ -39,66 +40,27 @@ class ModelApiResponse(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelApiResponse from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelApiResponse from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "code": obj.get("code"), - "type": obj.get("type"), - "message": obj.get("message") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/model_field.py b/samples/openapi3/client/petstore/python/petstore_api/models/model_field.py index d7b03848fe16..b6af02e8f48d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/model_field.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/model_field.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelField(BaseModel): """ @@ -37,64 +38,27 @@ class ModelField(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelField from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelField from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "field": obj.get("field") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/model_return.py b/samples/openapi3/client/petstore/python/petstore_api/models/model_return.py index 3f2558bc6e7d..6fc7eba6d7c3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/model_return.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/model_return.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ModelReturn(BaseModel): """ @@ -37,64 +38,27 @@ class ModelReturn(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ModelReturn from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ModelReturn from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "return": obj.get("return") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/multi_arrays.py b/samples/openapi3/client/petstore/python/petstore_api/models/multi_arrays.py index 80fa67f8a11c..55964857c0c3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/multi_arrays.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/multi_arrays.py @@ -22,7 +22,8 @@ from petstore_api.models.file import File from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class MultiArrays(BaseModel): """ @@ -40,79 +41,27 @@ class MultiArrays(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of MultiArrays from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - # override the default output from pydantic by calling `to_dict()` of each item in files (list) - _items = [] - if self.files: - for _item_files in self.files: - if _item_files: - _items.append(_item_files.to_dict()) - _dict['files'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of MultiArrays from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/name.py b/samples/openapi3/client/petstore/python/petstore_api/models/name.py index 01b02f834137..9a9cc14ecb63 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/name.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Name(BaseModel): """ @@ -40,71 +41,27 @@ class Name(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Name from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * OpenAPI `readOnly` fields are excluded. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "snake_case", - "var_123_number", - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Name from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name"), - "snake_case": obj.get("snake_case"), - "property": obj.get("property"), - "123Number": obj.get("123Number") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py index cb27fbf691c2..e3244d22b190 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictFloat, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NullableClass(BaseModel): """ @@ -50,131 +51,27 @@ class NullableClass(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NullableClass from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if required_integer_prop (nullable) is None - # and model_fields_set contains the field - if self.required_integer_prop is None and "required_integer_prop" in self.model_fields_set: - _dict['required_integer_prop'] = None - - # set to None if integer_prop (nullable) is None - # and model_fields_set contains the field - if self.integer_prop is None and "integer_prop" in self.model_fields_set: - _dict['integer_prop'] = None - - # set to None if number_prop (nullable) is None - # and model_fields_set contains the field - if self.number_prop is None and "number_prop" in self.model_fields_set: - _dict['number_prop'] = None - - # set to None if boolean_prop (nullable) is None - # and model_fields_set contains the field - if self.boolean_prop is None and "boolean_prop" in self.model_fields_set: - _dict['boolean_prop'] = None - - # set to None if string_prop (nullable) is None - # and model_fields_set contains the field - if self.string_prop is None and "string_prop" in self.model_fields_set: - _dict['string_prop'] = None - - # set to None if date_prop (nullable) is None - # and model_fields_set contains the field - if self.date_prop is None and "date_prop" in self.model_fields_set: - _dict['date_prop'] = None - - # set to None if datetime_prop (nullable) is None - # and model_fields_set contains the field - if self.datetime_prop is None and "datetime_prop" in self.model_fields_set: - _dict['datetime_prop'] = None - - # set to None if array_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.array_nullable_prop is None and "array_nullable_prop" in self.model_fields_set: - _dict['array_nullable_prop'] = None - - # set to None if array_and_items_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.array_and_items_nullable_prop is None and "array_and_items_nullable_prop" in self.model_fields_set: - _dict['array_and_items_nullable_prop'] = None - - # set to None if object_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.object_nullable_prop is None and "object_nullable_prop" in self.model_fields_set: - _dict['object_nullable_prop'] = None - - # set to None if object_and_items_nullable_prop (nullable) is None - # and model_fields_set contains the field - if self.object_and_items_nullable_prop is None and "object_and_items_nullable_prop" in self.model_fields_set: - _dict['object_and_items_nullable_prop'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NullableClass from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "required_integer_prop": obj.get("required_integer_prop"), - "integer_prop": obj.get("integer_prop"), - "number_prop": obj.get("number_prop"), - "boolean_prop": obj.get("boolean_prop"), - "string_prop": obj.get("string_prop"), - "date_prop": obj.get("date_prop"), - "datetime_prop": obj.get("datetime_prop"), - "array_nullable_prop": obj.get("array_nullable_prop"), - "array_and_items_nullable_prop": obj.get("array_and_items_nullable_prop"), - "array_items_nullable": obj.get("array_items_nullable"), - "object_nullable_prop": obj.get("object_nullable_prop"), - "object_and_items_nullable_prop": obj.get("object_and_items_nullable_prop"), - "object_items_nullable": obj.get("object_items_nullable") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_property.py b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_property.py index e73cd1509c90..9e529cbfd0e5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_property.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_property.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NullableProperty(BaseModel): """ @@ -49,70 +50,27 @@ def name_validate_regular_expression(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NullableProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if name (nullable) is None - # and model_fields_set contains the field - if self.name is None and "name" in self.model_fields_set: - _dict['name'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NullableProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/number_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/number_only.py index f74010e908bb..79b3e4c7dd1f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/number_only.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictFloat from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class NumberOnly(BaseModel): """ @@ -37,64 +38,27 @@ class NumberOnly(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of NumberOnly from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of NumberOnly from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "JustNumber": obj.get("JustNumber") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/object_to_test_additional_properties.py b/samples/openapi3/client/petstore/python/petstore_api/models/object_to_test_additional_properties.py index 097bdd34e2be..a3efd1d44032 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/object_to_test_additional_properties.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/object_to_test_additional_properties.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ObjectToTestAdditionalProperties(BaseModel): """ @@ -37,64 +38,27 @@ class ObjectToTestAdditionalProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ObjectToTestAdditionalProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ObjectToTestAdditionalProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "property": obj.get("property") if obj.get("property") is not None else False - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/object_with_deprecated_fields.py b/samples/openapi3/client/petstore/python/petstore_api/models/object_with_deprecated_fields.py index 0c0cc840680b..2e952365e91e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/object_with_deprecated_fields.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/object_with_deprecated_fields.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.deprecated_object import DeprecatedObject from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ObjectWithDeprecatedFields(BaseModel): """ @@ -41,70 +42,27 @@ class ObjectWithDeprecatedFields(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ObjectWithDeprecatedFields from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of deprecated_ref - if self.deprecated_ref: - _dict['deprecatedRef'] = self.deprecated_ref.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ObjectWithDeprecatedFields from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "uuid": obj.get("uuid"), - "id": obj.get("id"), - "deprecatedRef": DeprecatedObject.from_dict(obj["deprecatedRef"]) if obj.get("deprecatedRef") is not None else None, - "bars": obj.get("bars") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py b/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py index f180178737db..bdbbebe0e1c4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py @@ -19,119 +19,55 @@ from typing import Any, List, Optional from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self ONEOFENUMSTRING_ONE_OF_SCHEMAS = ["EnumString1", "EnumString2"] -class OneOfEnumString(BaseModel): +class OneOfEnumString(RootModel[Union[EnumString1, EnumString2]]): """ oneOf enum strings """ - # data type: EnumString1 - oneof_schema_1_validator: Optional[EnumString1] = None - # data type: EnumString2 - oneof_schema_2_validator: Optional[EnumString2] = None - actual_instance: Optional[Union[EnumString1, EnumString2]] = None - one_of_schemas: Set[str] = { "EnumString1", "EnumString2" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[EnumString1, EnumString2] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = OneOfEnumString.model_construct() - error_messages = [] - match = 0 - # validate data type: EnumString1 - if not isinstance(v, EnumString1): - error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString1`") - else: - match += 1 - # validate data type: EnumString2 - if not isinstance(v, EnumString2): - error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString2`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into EnumString1 - try: - instance.actual_instance = EnumString1.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into EnumString2 - try: - instance.actual_instance = EnumString2.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], EnumString1, EnumString2]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/order.py b/samples/openapi3/client/petstore/python/petstore_api/models/order.py index 12dd1ef117d2..3d94af52c8e3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/order.py @@ -21,7 +21,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Order(BaseModel): """ @@ -31,7 +32,10 @@ class Order(BaseModel): pet_id: Optional[StrictInt] = Field(default=None, alias="petId") quantity: Optional[StrictInt] = None ship_date: Optional[datetime] = Field(default=None, alias="shipDate") - status: Optional[StrictStr] = Field(default=None, description="Order Status") + status: Optional[Literal['placed', 'approved', 'delivered']] = Field( + None, + description="Order Status" + ) complete: Optional[StrictBool] = False additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["id", "petId", "quantity", "shipDate", "status", "complete"] @@ -53,69 +57,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Order from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Order from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "petId": obj.get("petId"), - "quantity": obj.get("quantity"), - "shipDate": obj.get("shipDate"), - "status": obj.get("status"), - "complete": obj.get("complete") if obj.get("complete") is not None else False - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/outer_composite.py b/samples/openapi3/client/petstore/python/petstore_api/models/outer_composite.py index 5242660b636b..49a79eb0a32f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/outer_composite.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/outer_composite.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictBool, StrictFloat, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class OuterComposite(BaseModel): """ @@ -39,66 +40,27 @@ class OuterComposite(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of OuterComposite from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of OuterComposite from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "my_number": obj.get("my_number"), - "my_string": obj.get("my_string"), - "my_boolean": obj.get("my_boolean") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/outer_object_with_enum_property.py b/samples/openapi3/client/petstore/python/petstore_api/models/outer_object_with_enum_property.py index f8d215a21c94..6de09c15996d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/outer_object_with_enum_property.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/outer_object_with_enum_property.py @@ -22,7 +22,8 @@ from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_integer import OuterEnumInteger from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class OuterObjectWithEnumProperty(BaseModel): """ @@ -40,70 +41,27 @@ class OuterObjectWithEnumProperty(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of OuterObjectWithEnumProperty from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - # set to None if str_value (nullable) is None - # and model_fields_set contains the field - if self.str_value is None and "str_value" in self.model_fields_set: - _dict['str_value'] = None - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of OuterObjectWithEnumProperty from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "str_value": obj.get("str_value"), - "value": obj.get("value") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/parent.py b/samples/openapi3/client/petstore/python/petstore_api/models/parent.py index 8a30758ab8fd..d9590e69f6dc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/parent.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/parent.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Parent(BaseModel): """ @@ -38,76 +39,27 @@ class Parent(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Parent from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) - _field_dict = {} - if self.optional_dict: - for _key_optional_dict in self.optional_dict: - if self.optional_dict[_key_optional_dict]: - _field_dict[_key_optional_dict] = self.optional_dict[_key_optional_dict].to_dict() - _dict['optionalDict'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Parent from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "optionalDict": dict( - (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj["optionalDict"].items() - ) - if obj.get("optionalDict") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/parent_with_optional_dict.py b/samples/openapi3/client/petstore/python/petstore_api/models/parent_with_optional_dict.py index 509693dd1441..87d0b13f8526 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/parent_with_optional_dict.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/parent_with_optional_dict.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ParentWithOptionalDict(BaseModel): """ @@ -38,76 +39,27 @@ class ParentWithOptionalDict(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ParentWithOptionalDict from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) - _field_dict = {} - if self.optional_dict: - for _key_optional_dict in self.optional_dict: - if self.optional_dict[_key_optional_dict]: - _field_dict[_key_optional_dict] = self.optional_dict[_key_optional_dict].to_dict() - _dict['optionalDict'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ParentWithOptionalDict from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "optionalDict": dict( - (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj["optionalDict"].items() - ) - if obj.get("optionalDict") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python/petstore_api/models/pet.py index 48f0c2fceeb7..d09bb6d73414 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/pet.py @@ -23,7 +23,8 @@ from petstore_api.models.category import Category from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Pet(BaseModel): """ @@ -34,7 +35,10 @@ class Pet(BaseModel): name: StrictStr photo_urls: Annotated[List[StrictStr], Field(min_length=0)] = Field(alias="photoUrls") tags: Optional[List[Tag]] = None - status: Optional[StrictStr] = Field(default=None, description="pet status in the store") + status: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["id", "category", "name", "photoUrls", "tags", "status"] @@ -55,79 +59,27 @@ def status_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Pet from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of category - if self.category: - _dict['category'] = self.category.to_dict() - # override the default output from pydantic by calling `to_dict()` of each item in tags (list) - _items = [] - if self.tags: - for _item_tags in self.tags: - if _item_tags: - _items.append(_item_tags.to_dict()) - _dict['tags'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Pet from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, - "name": obj.get("name"), - "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, - "status": obj.get("status") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/pig.py index 06798245b8fe..6646e6d477cd 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/pig.py @@ -19,137 +19,55 @@ from typing import Any, List, Optional from petstore_api.models.basque_pig import BasquePig from petstore_api.models.danish_pig import DanishPig -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] -class Pig(BaseModel): +class Pig(RootModel[Union[BasquePig, DanishPig]]): """ Pig """ - # data type: BasquePig - oneof_schema_1_validator: Optional[BasquePig] = None - # data type: DanishPig - oneof_schema_2_validator: Optional[DanishPig] = None - actual_instance: Optional[Union[BasquePig, DanishPig]] = None - one_of_schemas: Set[str] = { "BasquePig", "DanishPig" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[BasquePig, DanishPig] = Field( + ..., discriminator="class_name" ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - discriminator_value_class_map: Dict[str, str] = { - } - - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = Pig.model_construct() - error_messages = [] - match = 0 - # validate data type: BasquePig - if not isinstance(v, BasquePig): - error_messages.append(f"Error! Input type `{type(v)}` is not `BasquePig`") - else: - match += 1 - # validate data type: DanishPig - if not isinstance(v, DanishPig): - error_messages.append(f"Error! Input type `{type(v)}` is not `DanishPig`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # use oneOf discriminator to lookup the data type - _data_type = json.loads(json_str).get("className") - if not _data_type: - raise ValueError("Failed to lookup data type from the field `className` in the input.") - - # check if data type is `BasquePig` - if _data_type == "BasquePig": - instance.actual_instance = BasquePig.from_json(json_str) - return instance - - # check if data type is `DanishPig` - if _data_type == "DanishPig": - instance.actual_instance = DanishPig.from_json(json_str) - return instance - - # deserialize data into BasquePig - try: - instance.actual_instance = BasquePig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into DanishPig - try: - instance.actual_instance = DanishPig.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into Pig with oneOf schemas: BasquePig, DanishPig. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/pony_sizes.py b/samples/openapi3/client/petstore/python/petstore_api/models/pony_sizes.py index 74efce9a4d06..0de6140219e3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/pony_sizes.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/pony_sizes.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.type import Type from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PonySizes(BaseModel): """ @@ -38,64 +39,27 @@ class PonySizes(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PonySizes from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PonySizes from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "type": obj.get("type") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/poop_cleaning.py b/samples/openapi3/client/petstore/python/petstore_api/models/poop_cleaning.py index 76eb72a941bf..b04faac7e90d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/poop_cleaning.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/poop_cleaning.py @@ -20,14 +20,23 @@ from pydantic import BaseModel, ConfigDict, StrictStr, field_validator from typing import Any, ClassVar, Dict, List from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PoopCleaning(BaseModel): """ PoopCleaning """ # noqa: E501 - task_name: StrictStr - function_name: StrictStr + task_name: Literal['cleaning'] = Field( + ..., + description="task_name of the PoopCleaning", + alias="task_name" + ) + function_name: Literal['care'] = Field( + ..., + description="function_name of the PoopCleaning", + alias="function_name" + ) content: StrictStr additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["task_name", "function_name", "content"] @@ -53,66 +62,27 @@ def function_name_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PoopCleaning from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PoopCleaning from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "task_name": obj.get("task_name"), - "function_name": obj.get("function_name"), - "content": obj.get("content") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/primitive_string.py b/samples/openapi3/client/petstore/python/petstore_api/models/primitive_string.py index f7a971519f2f..6453538594f7 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/primitive_string.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/primitive_string.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.base_discriminator import BaseDiscriminator from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PrimitiveString(BaseDiscriminator): """ @@ -38,65 +39,27 @@ class PrimitiveString(BaseDiscriminator): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PrimitiveString from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PrimitiveString from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_typeName": obj.get("_typeName"), - "_value": obj.get("_value") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/property_map.py b/samples/openapi3/client/petstore/python/petstore_api/models/property_map.py index 0da2a14293de..df57d2c77660 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/property_map.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/property_map.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PropertyMap(BaseModel): """ @@ -38,76 +39,27 @@ class PropertyMap(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PropertyMap from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in some_data (dict) - _field_dict = {} - if self.some_data: - for _key_some_data in self.some_data: - if self.some_data[_key_some_data]: - _field_dict[_key_some_data] = self.some_data[_key_some_data].to_dict() - _dict['some_data'] = _field_dict - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PropertyMap from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "some_data": dict( - (_k, Tag.from_dict(_v)) - for _k, _v in obj["some_data"].items() - ) - if obj.get("some_data") is not None - else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/property_name_collision.py b/samples/openapi3/client/petstore/python/petstore_api/models/property_name_collision.py index d07aef22cd82..2044934c0750 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/property_name_collision.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/property_name_collision.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class PropertyNameCollision(BaseModel): """ @@ -39,66 +40,27 @@ class PropertyNameCollision(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of PropertyNameCollision from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of PropertyNameCollision from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_type": obj.get("_type"), - "type": obj.get("type"), - "type_": obj.get("type_") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/read_only_first.py b/samples/openapi3/client/petstore/python/petstore_api/models/read_only_first.py index 5a4155fcfa13..c90ba68dd356 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/read_only_first.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/read_only_first.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class ReadOnlyFirst(BaseModel): """ @@ -38,67 +39,27 @@ class ReadOnlyFirst(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of ReadOnlyFirst from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * OpenAPI `readOnly` fields are excluded. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "bar", - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of ReadOnlyFirst from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "bar": obj.get("bar"), - "baz": obj.get("baz") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/second_circular_all_of_ref.py b/samples/openapi3/client/petstore/python/petstore_api/models/second_circular_all_of_ref.py index 13d6327314c3..70d780804255 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/second_circular_all_of_ref.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/second_circular_all_of_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SecondCircularAllOfRef(BaseModel): """ @@ -38,73 +39,28 @@ class SecondCircularAllOfRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SecondCircularAllOfRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each item in circular_all_of_ref (list) - _items = [] - if self.circular_all_of_ref: - for _item_circular_all_of_ref in self.circular_all_of_ref: - if _item_circular_all_of_ref: - _items.append(_item_circular_all_of_ref.to_dict()) - _dict['circularAllOfRef'] = _items - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SecondCircularAllOfRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "_name": obj.get("_name"), - "circularAllOfRef": [CircularAllOfRef.from_dict(_item) for _item in obj["circularAllOfRef"]] if obj.get("circularAllOfRef") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.circular_all_of_ref import CircularAllOfRef # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/second_ref.py b/samples/openapi3/client/petstore/python/petstore_api/models/second_ref.py index 701e0dccaacf..79c38f4ea4ae 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/second_ref.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/second_ref.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SecondRef(BaseModel): """ @@ -38,69 +39,28 @@ class SecondRef(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SecondRef from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of circular_ref - if self.circular_ref: - _dict['circular_ref'] = self.circular_ref.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SecondRef from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "category": obj.get("category"), - "circular_ref": CircularReferenceModel.from_dict(obj["circular_ref"]) if obj.get("circular_ref") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.circular_reference_model import CircularReferenceModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/self_reference_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/self_reference_model.py index 0273b10dada6..0b2dea762dcc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/self_reference_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/self_reference_model.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SelfReferenceModel(BaseModel): """ @@ -38,69 +39,28 @@ class SelfReferenceModel(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SelfReferenceModel from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested - if self.nested: - _dict['nested'] = self.nested.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SelfReferenceModel from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested": DummyModel.from_dict(obj["nested"]) if obj.get("nested") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj from petstore_api.models.dummy_model import DummyModel # TODO: Rewrite to not use raise_errors diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/special_model_name.py b/samples/openapi3/client/petstore/python/petstore_api/models/special_model_name.py index 84686054875a..8eabe68b9eb3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/special_model_name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/special_model_name.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SpecialModelName(BaseModel): """ @@ -37,64 +38,27 @@ class SpecialModelName(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SpecialModelName from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SpecialModelName from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "$special[property.name]": obj.get("$special[property.name]") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py b/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py index e43761d33dfc..52aa54ac7019 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.category import Category from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class SpecialName(BaseModel): """ @@ -29,7 +30,10 @@ class SpecialName(BaseModel): """ # noqa: E501 var_property: Optional[StrictInt] = Field(default=None, alias="property") var_async: Optional[Category] = Field(default=None, alias="async") - var_schema: Optional[StrictStr] = Field(default=None, description="pet status in the store", alias="schema") + var_schema: Optional[Literal['available', 'pending', 'sold']] = Field( + None, + description="pet status in the store" + ) additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["property", "async", "schema"] @@ -50,69 +54,27 @@ def var_schema_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of SpecialName from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of var_async - if self.var_async: - _dict['async'] = self.var_async.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of SpecialName from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "property": obj.get("property"), - "async": Category.from_dict(obj["async"]) if obj.get("async") is not None else None, - "schema": obj.get("schema") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/tag.py b/samples/openapi3/client/petstore/python/petstore_api/models/tag.py index b3893aecb683..5b8ee944ee7b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/tag.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/tag.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tag(BaseModel): """ @@ -38,65 +39,27 @@ class Tag(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tag from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tag from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/task.py b/samples/openapi3/client/petstore/python/petstore_api/models/task.py index a8e0fa11ff84..c37aafc8762a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/task.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/task.py @@ -22,7 +22,8 @@ from uuid import UUID from petstore_api.models.task_activity import TaskActivity from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Task(BaseModel): """ @@ -40,68 +41,27 @@ class Task(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Task from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of activity - if self.activity: - _dict['activity'] = self.activity.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Task from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "activity": TaskActivity.from_dict(obj["activity"]) if obj.get("activity") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py b/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py index cc1e1fc5a60f..39a1c0bbc375 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/task_activity.py @@ -20,132 +20,55 @@ from petstore_api.models.bathing import Bathing from petstore_api.models.feeding import Feeding from petstore_api.models.poop_cleaning import PoopCleaning -from pydantic import StrictStr, Field +from pydantic import StrictStr, Field, RootModel from typing import Union, List, Set, Optional, Dict from typing_extensions import Literal, Self TASKACTIVITY_ONE_OF_SCHEMAS = ["Bathing", "Feeding", "PoopCleaning"] -class TaskActivity(BaseModel): +class TaskActivity(RootModel[Union[Bathing, Feeding, PoopCleaning]]): """ TaskActivity """ - # data type: PoopCleaning - oneof_schema_1_validator: Optional[PoopCleaning] = None - # data type: Feeding - oneof_schema_2_validator: Optional[Feeding] = None - # data type: Bathing - oneof_schema_3_validator: Optional[Bathing] = None - actual_instance: Optional[Union[Bathing, Feeding, PoopCleaning]] = None - one_of_schemas: Set[str] = { "Bathing", "Feeding", "PoopCleaning" } - - model_config = ConfigDict( - validate_assignment=True, - protected_namespaces=(), + root: Union[Bathing, Feeding, PoopCleaning] = Field( + ... ) + def __getattr__(self, name): + """ + Delegate attribute access to the root model if the attribute + doesn't exist on the main class. + """ - def __init__(self, *args, **kwargs) -> None: - if args: - if len(args) > 1: - raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") - if kwargs: - raise ValueError("If a position argument is used, keyword arguments cannot be used.") - super().__init__(actual_instance=args[0]) - else: - super().__init__(**kwargs) - - @field_validator('actual_instance') - def actual_instance_must_validate_oneof(cls, v): - instance = TaskActivity.model_construct() - error_messages = [] - match = 0 - # validate data type: PoopCleaning - if not isinstance(v, PoopCleaning): - error_messages.append(f"Error! Input type `{type(v)}` is not `PoopCleaning`") - else: - match += 1 - # validate data type: Feeding - if not isinstance(v, Feeding): - error_messages.append(f"Error! Input type `{type(v)}` is not `Feeding`") - else: - match += 1 - # validate data type: Bathing - if not isinstance(v, Bathing): - error_messages.append(f"Error! Input type `{type(v)}` is not `Bathing`") - else: - match += 1 - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when setting `actual_instance` in TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - else: - return v + if name in self.__dict__: + return super().__getattribute__(name) + + root = self.__dict__.get('root') + if root is not None: + return getattr(root, name) + + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") @classmethod - def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: - return cls.from_json(json.dumps(obj)) + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod def from_json(cls, json_str: str) -> Self: """Returns the object represented by the json string""" - instance = cls.model_construct() - error_messages = [] - match = 0 - - # deserialize data into PoopCleaning - try: - instance.actual_instance = PoopCleaning.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into Feeding - try: - instance.actual_instance = Feeding.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - # deserialize data into Bathing - try: - instance.actual_instance = Bathing.from_json(json_str) - match += 1 - except (ValidationError, ValueError) as e: - error_messages.append(str(e)) - - if match > 1: - # more than 1 match - raise ValueError("Multiple matches found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - elif match == 0: - # no match - raise ValueError("No match found when deserializing the JSON string into TaskActivity with oneOf schemas: Bathing, Feeding, PoopCleaning. Details: " + ", ".join(error_messages)) - else: - return instance + return cls.model_validate_json(json_str) def to_json(self) -> str: """Returns the JSON representation of the actual instance""" - if self.actual_instance is None: - return "null" + return self.model_dump_json(by_alias=True, exclude_none=True) - if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): - return self.actual_instance.to_json() - else: - return json.dumps(self.actual_instance) - - def to_dict(self) -> Optional[Union[Dict[str, Any], Bathing, Feeding, PoopCleaning]]: + def to_dict(self) -> Dict[str, Any]: """Returns the dict representation of the actual instance""" - if self.actual_instance is None: - return None - - if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): - return self.actual_instance.to_dict() - else: - # primitive type - return self.actual_instance + return self.model_dump(by_alias=True) def to_str(self) -> str: """Returns the string representation of the actual instance""" - return pprint.pformat(self.model_dump()) + return pprint.pformat(self.model_dump(by_alias=True, mode="json")) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model400_response.py index f5fe068c9111..cc234881eb3b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model400_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model400_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestErrorResponsesWithModel400Response(BaseModel): """ @@ -37,64 +38,27 @@ class TestErrorResponsesWithModel400Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel400Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel400Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "reason400": obj.get("reason400") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model404_response.py index 39e6c512ed3e..5cefd03da6cf 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model404_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model404_response.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestErrorResponsesWithModel404Response(BaseModel): """ @@ -37,64 +38,27 @@ class TestErrorResponsesWithModel404Response(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel404Response from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestErrorResponsesWithModel404Response from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "reason404": obj.get("reason404") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/test_inline_freeform_additional_properties_request.py b/samples/openapi3/client/petstore/python/petstore_api/models/test_inline_freeform_additional_properties_request.py index 7b93d84864f2..83309fd58987 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/test_inline_freeform_additional_properties_request.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/test_inline_freeform_additional_properties_request.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): """ @@ -37,64 +38,27 @@ class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "someProperty": obj.get("someProperty") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/test_model_with_enum_default.py b/samples/openapi3/client/petstore/python/petstore_api/models/test_model_with_enum_default.py index 4bff5e699a37..103ee7667394 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/test_model_with_enum_default.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/test_model_with_enum_default.py @@ -22,7 +22,8 @@ from petstore_api.models.test_enum import TestEnum from petstore_api.models.test_enum_with_default import TestEnumWithDefault from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestModelWithEnumDefault(BaseModel): """ @@ -32,7 +33,10 @@ class TestModelWithEnumDefault(BaseModel): test_string: Optional[StrictStr] = None test_enum_with_default: Optional[TestEnumWithDefault] = TestEnumWithDefault.ZWEI test_string_with_default: Optional[StrictStr] = 'ahoy matey' - test_inline_defined_enum_with_default: Optional[StrictStr] = 'B' + test_inline_defined_enum_with_default: Optional[Literal['A', 'B', 'C']] = Field( + None, + description="test_inline_defined_enum_with_default of the TestModelWithEnumDefault" + ) additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["test_enum", "test_string", "test_enum_with_default", "test_string_with_default", "test_inline_defined_enum_with_default"] @@ -53,68 +57,27 @@ def test_inline_defined_enum_with_default_validate_enum(cls, value): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestModelWithEnumDefault from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestModelWithEnumDefault from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "test_enum": obj.get("test_enum"), - "test_string": obj.get("test_string"), - "test_enum_with_default": obj.get("test_enum_with_default") if obj.get("test_enum_with_default") is not None else TestEnumWithDefault.ZWEI, - "test_string_with_default": obj.get("test_string_with_default") if obj.get("test_string_with_default") is not None else 'ahoy matey', - "test_inline_defined_enum_with_default": obj.get("test_inline_defined_enum_with_default") if obj.get("test_inline_defined_enum_with_default") is not None else 'B' - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/test_object_for_multipart_requests_request_marker.py b/samples/openapi3/client/petstore/python/petstore_api/models/test_object_for_multipart_requests_request_marker.py index c31d72482d59..cfd79254cbe9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/test_object_for_multipart_requests_request_marker.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/test_object_for_multipart_requests_request_marker.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class TestObjectForMultipartRequestsRequestMarker(BaseModel): """ @@ -37,64 +38,27 @@ class TestObjectForMultipartRequestsRequestMarker(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of TestObjectForMultipartRequestsRequestMarker from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of TestObjectForMultipartRequestsRequestMarker from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/tiger.py b/samples/openapi3/client/petstore/python/petstore_api/models/tiger.py index c2dab004fe1a..7d2c375e47e0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/tiger.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/tiger.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class Tiger(BaseModel): """ @@ -37,64 +38,27 @@ class Tiger(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of Tiger from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of Tiger from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "skill": obj.get("skill") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py b/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py index e5b5cb4ddeda..3717b3d245bc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py @@ -21,7 +21,8 @@ from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.creature_info import CreatureInfo from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UnnamedDictWithAdditionalModelListProperties(BaseModel): """ @@ -38,80 +39,27 @@ class UnnamedDictWithAdditionalModelListProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of each value in dict_property (dict of array) - _field_dict_of_array = {} - if self.dict_property: - for _key_dict_property in self.dict_property: - if self.dict_property[_key_dict_property] is not None: - _field_dict_of_array[_key_dict_property] = [ - _item.to_dict() for _item in self.dict_property[_key_dict_property] - ] - _dict['dictProperty'] = _field_dict_of_array - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalModelListProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "dictProperty": dict( - (_k, - [CreatureInfo.from_dict(_item) for _item in _v] - if _v is not None - else None - ) - for _k, _v in obj.get("dictProperty", {}).items() - ) - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py b/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py index f4c7625325c8..90cbb19b8e9e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UnnamedDictWithAdditionalStringListProperties(BaseModel): """ @@ -37,64 +38,27 @@ class UnnamedDictWithAdditionalStringListProperties(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UnnamedDictWithAdditionalStringListProperties from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "dictProperty": obj.get("dictProperty") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py index 6d79131bfe79..0a689487b4c5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): """ @@ -37,64 +38,27 @@ class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "name": obj.get("name") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/user.py b/samples/openapi3/client/petstore/python/petstore_api/models/user.py index ceeb6d4ae54c..3e775dd2e752 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/user.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/user.py @@ -20,7 +20,8 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class User(BaseModel): """ @@ -44,71 +45,27 @@ class User(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of User from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of User from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "id": obj.get("id"), - "username": obj.get("username"), - "firstName": obj.get("firstName"), - "lastName": obj.get("lastName"), - "email": obj.get("email"), - "password": obj.get("password"), - "phone": obj.get("phone"), - "userStatus": obj.get("userStatus") - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/with_nested_one_of.py b/samples/openapi3/client/petstore/python/petstore_api/models/with_nested_one_of.py index eb7e90879e90..c088f14d6330 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/with_nested_one_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/with_nested_one_of.py @@ -22,7 +22,8 @@ from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.pig import Pig from typing import Optional, Set -from typing_extensions import Self +from typing_extensions import Self, Literal +from pydantic import Field class WithNestedOneOf(BaseModel): """ @@ -41,72 +42,27 @@ class WithNestedOneOf(BaseModel): ) - def to_str(self) -> str: - """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) - - def to_json(self) -> str: - """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead - return json.dumps(self.to_dict()) + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + """Returns the object represented by the Dict""" + return cls.model_validate(obj, strict=True) @classmethod - def from_json(cls, json_str: str) -> Optional[Self]: - """Create an instance of WithNestedOneOf from a JSON string""" - return cls.from_dict(json.loads(json_str)) + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + return cls.model_validate_json(json_str) + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + return self.model_dump_json(by_alias=True, exclude_none=True) def to_dict(self) -> Dict[str, Any]: - """Return the dictionary representation of the model using alias. - - This has the following differences from calling pydantic's - `self.model_dump(by_alias=True)`: - - * `None` is only added to the output dict for nullable fields that - were set at model initialization. Other fields with value `None` - are ignored. - * Fields in `self.additional_properties` are added to the output dict. - """ - excluded_fields: Set[str] = set([ - "additional_properties", - ]) - - _dict = self.model_dump( - by_alias=True, - exclude=excluded_fields, - exclude_none=True, - ) - # override the default output from pydantic by calling `to_dict()` of nested_pig - if self.nested_pig: - _dict['nested_pig'] = self.nested_pig.to_dict() - # override the default output from pydantic by calling `to_dict()` of nested_oneof_enum_string - if self.nested_oneof_enum_string: - _dict['nested_oneof_enum_string'] = self.nested_oneof_enum_string.to_dict() - # puts key-value pairs in additional_properties in the top level - if self.additional_properties is not None: - for _key, _value in self.additional_properties.items(): - _dict[_key] = _value - - return _dict + """Returns the dict representation of the actual instance""" + return self.model_dump(by_alias=True) + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @classmethod - def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: - """Create an instance of WithNestedOneOf from a dict""" - if obj is None: - return None - - if not isinstance(obj, dict): - return cls.model_validate(obj) - - _obj = cls.model_validate({ - "size": obj.get("size"), - "nested_pig": Pig.from_dict(obj["nested_pig"]) if obj.get("nested_pig") is not None else None, - "nested_oneof_enum_string": OneOfEnumString.from_dict(obj["nested_oneof_enum_string"]) if obj.get("nested_oneof_enum_string") is not None else None - }) - # store additional fields in additional_properties - for _key in obj.keys(): - if _key not in cls.__properties: - _obj.additional_properties[_key] = obj.get(_key) - - return _obj diff --git a/samples/openapi3/schema/petstore/avro-schema-issue6268/.openapi-generator/VERSION b/samples/openapi3/schema/petstore/avro-schema-issue6268/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/openapi3/schema/petstore/avro-schema-issue6268/.openapi-generator/VERSION +++ b/samples/openapi3/schema/petstore/avro-schema-issue6268/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION b/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION +++ b/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION +++ b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useApiVersioning/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useApiVersioning/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useApiVersioning/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useApiVersioning/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useAuthentication/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useAuthentication/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useAuthentication/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useAuthentication/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useProblemDetails/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useProblemDetails/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useProblemDetails/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useProblemDetails/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useRecords/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useRecords/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useRecords/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useRecords/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useResponseCaching/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useResponseCaching/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useResponseCaching/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useResponseCaching/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints-useValidators/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints-useValidators/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/server/petstore/aspnet/fastendpoints-useValidators/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints-useValidators/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnet/fastendpoints/.openapi-generator/VERSION b/samples/server/petstore/aspnet/fastendpoints/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/server/petstore/aspnet/fastendpoints/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnet/fastendpoints/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-3.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-3.1/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Filters/BasePathFilter.cs b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Filters/BasePathFilter.cs index e69de29bb2d1..97ae99c9295a 100644 --- a/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Filters/BasePathFilter.cs +++ b/samples/server/petstore/aspnetcore-5.0/src/Org.OpenAPITools/Filters/BasePathFilter.cs @@ -0,0 +1,60 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.Linq; +using System.Text.RegularExpressions; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// BasePath Document Filter sets BasePath property of OpenAPI and removes it from the individual URL paths + /// + public class BasePathFilter : IDocumentFilter + { + /// + /// Constructor + /// + /// BasePath to remove from Operations + public BasePathFilter(string basePath) + { + BasePath = basePath; + } + + /// + /// Gets the BasePath of the OpenAPI Doc + /// + /// The BasePath of the OpenAPI Doc + public string BasePath { get; } + + /// + /// Apply the filter + /// + /// OpenApiDocument + /// FilterContext + public void Apply(OpenApiDocument openapiDoc, DocumentFilterContext context) + { + //openapiDoc.BasePath = BasePath; + + var pathsToModify = openapiDoc.Paths.Where(p => p.Key.StartsWith(BasePath)).ToList(); + + foreach (var (key, value) in pathsToModify) + { + if (key.StartsWith(BasePath)) + { + var newKey = Regex.Replace(key, $"^{BasePath}", string.Empty); + openapiDoc.Paths.Remove(key); + openapiDoc.Paths.Add(newKey, value); + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-6.0-pocoModels/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json index e69de29bb2d1..b47dce3d2c68 100644 --- a/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json @@ -0,0 +1,1203 @@ +{ + "openapi" : "3.0.0", + "info" : { + "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", + "license" : { + "name" : "Apache-2.0", + "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "title" : "OpenAPI Petstore", + "version" : "1.0.0" + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + }, + "servers" : [ { + "url" : "http://petstore.swagger.io/v2" + } ], + "tags" : [ { + "description" : "Everything about your Pets", + "name" : "pet" + }, { + "description" : "Access to Petstore orders", + "name" : "store" + }, { + "description" : "Operations about user", + "name" : "user" + } ], + "paths" : { + "/test" : { + "get" : { + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "testQuery", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/TestEnum" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "description" : "OK" + } + }, + "summary" : "Test API" + } + }, + "/pet" : { + "post" : { + "description" : "", + "operationId" : "addPet", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Add a new pet to the store", + "tags" : [ "pet" ] + }, + "put" : { + "description" : "", + "operationId" : "updatePet", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + }, + "405" : { + "description" : "Validation exception" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Update an existing pet", + "tags" : [ "pet" ] + } + }, + "/pet/findByStatus" : { + "get" : { + "description" : "Multiple status values can be provided with comma separated strings", + "operationId" : "findPetsByStatus", + "parameters" : [ { + "deprecated" : true, + "description" : "Status values that need to be considered for filter", + "explode" : false, + "in" : "query", + "name" : "status", + "required" : true, + "schema" : { + "items" : { + "default" : "available", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid status value" + } + }, + "security" : [ { + "petstore_auth" : [ "read:pets" ] + } ], + "summary" : "Finds Pets by status", + "tags" : [ "pet" ] + } + }, + "/pet/findByTags" : { + "get" : { + "deprecated" : true, + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "parameters" : [ { + "description" : "Tags to filter by", + "explode" : false, + "in" : "query", + "name" : "tags", + "required" : true, + "schema" : { + "items" : { + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid tag value" + } + }, + "security" : [ { + "petstore_auth" : [ "read:pets" ] + } ], + "summary" : "Finds Pets by tags", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}" : { + "delete" : { + "description" : "", + "operationId" : "deletePet", + "parameters" : [ { + "explode" : false, + "in" : "header", + "name" : "api_key", + "required" : false, + "schema" : { + "type" : "string" + }, + "style" : "simple" + }, { + "description" : "Pet id to delete", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid pet value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Deletes a pet", + "tags" : [ "pet" ] + }, + "get" : { + "description" : "Returns a single pet", + "operationId" : "getPetById", + "parameters" : [ { + "description" : "ID of pet to return", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Find pet by ID", + "tags" : [ "pet" ] + }, + "post" : { + "description" : "", + "operationId" : "updatePetWithForm", + "parameters" : [ { + "description" : "ID of pet that needs to be updated", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "application/x-www-form-urlencoded" : { + "schema" : { + "$ref" : "#/components/schemas/updatePetWithForm_request" + } + } + } + }, + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Updates a pet in the store with form data", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "description" : "", + "operationId" : "uploadFile", + "parameters" : [ { + "description" : "ID of pet to update", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "multipart/form-data" : { + "schema" : { + "$ref" : "#/components/schemas/uploadFile_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ApiResponse" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "uploads an image", + "tags" : [ "pet" ] + } + }, + "/store/inventory" : { + "get" : { + "description" : "Returns a map of status codes to quantities", + "operationId" : "getInventory", + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "additionalProperties" : { + "format" : "int32", + "type" : "integer" + }, + "type" : "object" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Returns pet inventories by status", + "tags" : [ "store" ] + } + }, + "/store/order" : { + "post" : { + "description" : "", + "operationId" : "placeOrder", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "order placed for purchasing the pet", + "required" : true + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid Order" + } + }, + "summary" : "Place an order for a pet", + "tags" : [ "store" ] + } + }, + "/store/order/{orderId}" : { + "delete" : { + "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId" : "deleteOrder", + "parameters" : [ { + "description" : "ID of the order that needs to be deleted", + "explode" : false, + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "summary" : "Delete purchase order by ID", + "tags" : [ "store" ] + }, + "get" : { + "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions", + "operationId" : "getOrderById", + "parameters" : [ { + "description" : "ID of pet that needs to be fetched", + "explode" : false, + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "format" : "int64", + "maximum" : 5, + "minimum" : 1, + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "summary" : "Find purchase order by ID", + "tags" : [ "store" ] + } + }, + "/user" : { + "post" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Created user object", + "required" : true + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Create user", + "tags" : [ "user" ] + } + }, + "/user/createWithArray" : { + "post" : { + "description" : "", + "operationId" : "createUsersWithArrayInput", + "requestBody" : { + "$ref" : "#/components/requestBodies/UserArray" + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ] + } + }, + "/user/createWithList" : { + "post" : { + "description" : "", + "operationId" : "createUsersWithListInput", + "requestBody" : { + "$ref" : "#/components/requestBodies/UserArray" + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ] + } + }, + "/user/login" : { + "get" : { + "description" : "", + "operationId" : "loginUser", + "parameters" : [ { + "description" : "The user name for login", + "explode" : true, + "in" : "query", + "name" : "username", + "required" : true, + "schema" : { + "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", + "type" : "string" + }, + "style" : "form" + }, { + "description" : "The password for login in clear text", + "explode" : true, + "in" : "query", + "name" : "password", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "type" : "string" + } + }, + "application/json" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "successful operation", + "headers" : { + "Set-Cookie" : { + "description" : "Cookie authentication key for use with the `api_key` apiKey authentication.", + "explode" : false, + "schema" : { + "example" : "AUTH_KEY=abcde12345; Path=/; HttpOnly", + "type" : "string" + }, + "style" : "simple" + }, + "X-Rate-Limit" : { + "description" : "calls per hour allowed by the user", + "explode" : false, + "schema" : { + "format" : "int32", + "type" : "integer" + }, + "style" : "simple" + }, + "X-Expires-After" : { + "description" : "date in UTC when token expires", + "explode" : false, + "schema" : { + "format" : "date-time", + "type" : "string" + }, + "style" : "simple" + } + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + }, + "summary" : "Logs user into the system", + "tags" : [ "user" ] + } + }, + "/user/logout" : { + "get" : { + "description" : "", + "operationId" : "logoutUser", + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Logs out current logged in user session", + "tags" : [ "user" ] + } + }, + "/user/{username}" : { + "delete" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "parameters" : [ { + "description" : "The name that needs to be deleted", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Delete user", + "tags" : [ "user" ] + }, + "get" : { + "description" : "", + "operationId" : "getUserByName", + "parameters" : [ { + "description" : "The name that needs to be fetched. Use user1 for testing.", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "summary" : "Get user by user name", + "tags" : [ "user" ] + }, + "put" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "parameters" : [ { + "description" : "name that need to be deleted", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Updated user object", + "required" : true + }, + "responses" : { + "400" : { + "description" : "Invalid user supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Updated user", + "tags" : [ "user" ] + } + }, + "/fake/parameter_example_test" : { + "get" : { + "description" : "", + "operationId" : "fake_parameter_example_test", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "data", + "required" : true, + "schema" : { + "$ref" : "#/components/schemas/Pet" + }, + "style" : "form" + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "summary" : "fake endpoint to test parameter example (object)", + "tags" : [ "fake" ] + } + }, + "/fake/nullable_example_test" : { + "get" : { + "description" : "", + "operationId" : "fake_nullable_example_test", + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TestNullable" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Fake endpoint to test nullable example (object)", + "tags" : [ "fake" ] + } + } + }, + "components" : { + "requestBodies" : { + "UserArray" : { + "content" : { + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/User" + }, + "type" : "array" + } + } + }, + "description" : "List of user object", + "required" : true + }, + "Pet" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "Pet object that needs to be added to the store", + "required" : true + } + }, + "schemas" : { + "TestEnum" : { + "enum" : [ "A", "B" ], + "type" : "string" + }, + "TestNullable" : { + "example" : { + "nullableName" : "nullableName", + "name" : "name" + }, + "properties" : { + "name" : { + "type" : "string" + }, + "nullableName" : { + "nullable" : true, + "type" : "string" + } + }, + "type" : "object" + }, + "Order" : { + "description" : "An order for a pets from the pet store", + "example" : { + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "petId" : { + "format" : "int64", + "type" : "integer" + }, + "quantity" : { + "format" : "int32", + "type" : "integer" + }, + "shipDate" : { + "format" : "date-time", + "type" : "string" + }, + "status" : { + "description" : "Order Status", + "enum" : [ "placed", "approved", "delivered" ], + "type" : "string" + }, + "complete" : { + "default" : false, + "type" : "boolean" + } + }, + "title" : "Pet Order", + "type" : "object", + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "description" : "A category for a pet", + "example" : { + "name" : "name", + "id" : 6 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", + "type" : "string" + } + }, + "title" : "Pet category", + "type" : "object", + "xml" : { + "name" : "Category" + } + }, + "User" : { + "description" : "A User who is purchasing from the pet store", + "example" : { + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "username" : { + "type" : "string" + }, + "firstName" : { + "type" : "string" + }, + "lastName" : { + "type" : "string" + }, + "email" : { + "type" : "string" + }, + "password" : { + "type" : "string" + }, + "phone" : { + "type" : "string" + }, + "userStatus" : { + "description" : "User Status", + "format" : "int32", + "type" : "integer" + } + }, + "title" : "a User", + "type" : "object", + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "description" : "A tag for a pet", + "example" : { + "name" : "name", + "id" : 1 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "type" : "object", + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "description" : "A pet for sale in the pet store", + "example" : { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "category" : { + "$ref" : "#/components/schemas/Category" + }, + "name" : { + "example" : "doggie", + "type" : "string" + }, + "photoUrls" : { + "items" : { + "type" : "string" + }, + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + } + }, + "tags" : { + "items" : { + "$ref" : "#/components/schemas/Tag" + }, + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + } + }, + "status" : { + "deprecated" : true, + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + } + }, + "required" : [ "name", "photoUrls" ], + "title" : "a Pet", + "type" : "object", + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "description" : "Describes the result of uploading an image resource", + "example" : { + "code" : 0, + "type" : "type", + "message" : "message" + }, + "properties" : { + "code" : { + "format" : "int32", + "type" : "integer" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "type" : "object" + }, + "Dog" : { + "allOf" : [ { + "$ref" : "#/components/schemas/Animal" + }, { + "properties" : { + "breed" : { + "type" : "string" + } + }, + "type" : "object" + } ] + }, + "Cat" : { + "allOf" : [ { + "$ref" : "#/components/schemas/Animal" + }, { + "properties" : { + "declawed" : { + "type" : "boolean" + } + }, + "type" : "object" + } ] + }, + "Animal" : { + "discriminator" : { + "mapping" : { + "DOG" : "#/components/schemas/Dog", + "CAT" : "#/components/schemas/Cat" + }, + "propertyName" : "className" + }, + "properties" : { + "className" : { + "type" : "string" + }, + "color" : { + "default" : "red", + "type" : "string" + } + }, + "required" : [ "className" ], + "type" : "object" + }, + "updatePetWithForm_request" : { + "properties" : { + "name" : { + "description" : "Updated name of the pet", + "type" : "string" + }, + "status" : { + "description" : "Updated status of the pet", + "type" : "string" + } + }, + "type" : "object" + }, + "uploadFile_request" : { + "properties" : { + "additionalMetadata" : { + "description" : "Additional data to pass to server", + "type" : "string" + }, + "file" : { + "description" : "file to upload", + "format" : "binary", + "type" : "string" + } + }, + "type" : "object" + } + }, + "securitySchemes" : { + "petstore_auth" : { + "flows" : { + "implicit" : { + "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", + "scopes" : { + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" + } + } + }, + "type" : "oauth2" + }, + "api_key" : { + "in" : "header", + "name" : "api_key", + "type" : "apiKey" + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-6.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-8.0-NewtonsoftFalse/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-8.0-nullableReferenceTypes/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/wwwroot/openapi-original.json index e69de29bb2d1..b47dce3d2c68 100644 --- a/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/wwwroot/openapi-original.json +++ b/samples/server/petstore/aspnetcore-8.0-pocoModels/src/Org.OpenAPITools/wwwroot/openapi-original.json @@ -0,0 +1,1203 @@ +{ + "openapi" : "3.0.0", + "info" : { + "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", + "license" : { + "name" : "Apache-2.0", + "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "title" : "OpenAPI Petstore", + "version" : "1.0.0" + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + }, + "servers" : [ { + "url" : "http://petstore.swagger.io/v2" + } ], + "tags" : [ { + "description" : "Everything about your Pets", + "name" : "pet" + }, { + "description" : "Access to Petstore orders", + "name" : "store" + }, { + "description" : "Operations about user", + "name" : "user" + } ], + "paths" : { + "/test" : { + "get" : { + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "testQuery", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/TestEnum" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "description" : "OK" + } + }, + "summary" : "Test API" + } + }, + "/pet" : { + "post" : { + "description" : "", + "operationId" : "addPet", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Add a new pet to the store", + "tags" : [ "pet" ] + }, + "put" : { + "description" : "", + "operationId" : "updatePet", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + }, + "405" : { + "description" : "Validation exception" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Update an existing pet", + "tags" : [ "pet" ] + } + }, + "/pet/findByStatus" : { + "get" : { + "description" : "Multiple status values can be provided with comma separated strings", + "operationId" : "findPetsByStatus", + "parameters" : [ { + "deprecated" : true, + "description" : "Status values that need to be considered for filter", + "explode" : false, + "in" : "query", + "name" : "status", + "required" : true, + "schema" : { + "items" : { + "default" : "available", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid status value" + } + }, + "security" : [ { + "petstore_auth" : [ "read:pets" ] + } ], + "summary" : "Finds Pets by status", + "tags" : [ "pet" ] + } + }, + "/pet/findByTags" : { + "get" : { + "deprecated" : true, + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "parameters" : [ { + "description" : "Tags to filter by", + "explode" : false, + "in" : "query", + "name" : "tags", + "required" : true, + "schema" : { + "items" : { + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid tag value" + } + }, + "security" : [ { + "petstore_auth" : [ "read:pets" ] + } ], + "summary" : "Finds Pets by tags", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}" : { + "delete" : { + "description" : "", + "operationId" : "deletePet", + "parameters" : [ { + "explode" : false, + "in" : "header", + "name" : "api_key", + "required" : false, + "schema" : { + "type" : "string" + }, + "style" : "simple" + }, { + "description" : "Pet id to delete", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid pet value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Deletes a pet", + "tags" : [ "pet" ] + }, + "get" : { + "description" : "Returns a single pet", + "operationId" : "getPetById", + "parameters" : [ { + "description" : "ID of pet to return", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Find pet by ID", + "tags" : [ "pet" ] + }, + "post" : { + "description" : "", + "operationId" : "updatePetWithForm", + "parameters" : [ { + "description" : "ID of pet that needs to be updated", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "application/x-www-form-urlencoded" : { + "schema" : { + "$ref" : "#/components/schemas/updatePetWithForm_request" + } + } + } + }, + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Updates a pet in the store with form data", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "description" : "", + "operationId" : "uploadFile", + "parameters" : [ { + "description" : "ID of pet to update", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "multipart/form-data" : { + "schema" : { + "$ref" : "#/components/schemas/uploadFile_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ApiResponse" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "uploads an image", + "tags" : [ "pet" ] + } + }, + "/store/inventory" : { + "get" : { + "description" : "Returns a map of status codes to quantities", + "operationId" : "getInventory", + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "additionalProperties" : { + "format" : "int32", + "type" : "integer" + }, + "type" : "object" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Returns pet inventories by status", + "tags" : [ "store" ] + } + }, + "/store/order" : { + "post" : { + "description" : "", + "operationId" : "placeOrder", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "order placed for purchasing the pet", + "required" : true + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid Order" + } + }, + "summary" : "Place an order for a pet", + "tags" : [ "store" ] + } + }, + "/store/order/{orderId}" : { + "delete" : { + "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId" : "deleteOrder", + "parameters" : [ { + "description" : "ID of the order that needs to be deleted", + "explode" : false, + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "summary" : "Delete purchase order by ID", + "tags" : [ "store" ] + }, + "get" : { + "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions", + "operationId" : "getOrderById", + "parameters" : [ { + "description" : "ID of pet that needs to be fetched", + "explode" : false, + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "format" : "int64", + "maximum" : 5, + "minimum" : 1, + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "summary" : "Find purchase order by ID", + "tags" : [ "store" ] + } + }, + "/user" : { + "post" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Created user object", + "required" : true + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Create user", + "tags" : [ "user" ] + } + }, + "/user/createWithArray" : { + "post" : { + "description" : "", + "operationId" : "createUsersWithArrayInput", + "requestBody" : { + "$ref" : "#/components/requestBodies/UserArray" + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ] + } + }, + "/user/createWithList" : { + "post" : { + "description" : "", + "operationId" : "createUsersWithListInput", + "requestBody" : { + "$ref" : "#/components/requestBodies/UserArray" + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ] + } + }, + "/user/login" : { + "get" : { + "description" : "", + "operationId" : "loginUser", + "parameters" : [ { + "description" : "The user name for login", + "explode" : true, + "in" : "query", + "name" : "username", + "required" : true, + "schema" : { + "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", + "type" : "string" + }, + "style" : "form" + }, { + "description" : "The password for login in clear text", + "explode" : true, + "in" : "query", + "name" : "password", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "type" : "string" + } + }, + "application/json" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "successful operation", + "headers" : { + "Set-Cookie" : { + "description" : "Cookie authentication key for use with the `api_key` apiKey authentication.", + "explode" : false, + "schema" : { + "example" : "AUTH_KEY=abcde12345; Path=/; HttpOnly", + "type" : "string" + }, + "style" : "simple" + }, + "X-Rate-Limit" : { + "description" : "calls per hour allowed by the user", + "explode" : false, + "schema" : { + "format" : "int32", + "type" : "integer" + }, + "style" : "simple" + }, + "X-Expires-After" : { + "description" : "date in UTC when token expires", + "explode" : false, + "schema" : { + "format" : "date-time", + "type" : "string" + }, + "style" : "simple" + } + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + }, + "summary" : "Logs user into the system", + "tags" : [ "user" ] + } + }, + "/user/logout" : { + "get" : { + "description" : "", + "operationId" : "logoutUser", + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Logs out current logged in user session", + "tags" : [ "user" ] + } + }, + "/user/{username}" : { + "delete" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "parameters" : [ { + "description" : "The name that needs to be deleted", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Delete user", + "tags" : [ "user" ] + }, + "get" : { + "description" : "", + "operationId" : "getUserByName", + "parameters" : [ { + "description" : "The name that needs to be fetched. Use user1 for testing.", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "summary" : "Get user by user name", + "tags" : [ "user" ] + }, + "put" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "parameters" : [ { + "description" : "name that need to be deleted", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Updated user object", + "required" : true + }, + "responses" : { + "400" : { + "description" : "Invalid user supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Updated user", + "tags" : [ "user" ] + } + }, + "/fake/parameter_example_test" : { + "get" : { + "description" : "", + "operationId" : "fake_parameter_example_test", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "data", + "required" : true, + "schema" : { + "$ref" : "#/components/schemas/Pet" + }, + "style" : "form" + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "summary" : "fake endpoint to test parameter example (object)", + "tags" : [ "fake" ] + } + }, + "/fake/nullable_example_test" : { + "get" : { + "description" : "", + "operationId" : "fake_nullable_example_test", + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TestNullable" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Fake endpoint to test nullable example (object)", + "tags" : [ "fake" ] + } + } + }, + "components" : { + "requestBodies" : { + "UserArray" : { + "content" : { + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/User" + }, + "type" : "array" + } + } + }, + "description" : "List of user object", + "required" : true + }, + "Pet" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "Pet object that needs to be added to the store", + "required" : true + } + }, + "schemas" : { + "TestEnum" : { + "enum" : [ "A", "B" ], + "type" : "string" + }, + "TestNullable" : { + "example" : { + "nullableName" : "nullableName", + "name" : "name" + }, + "properties" : { + "name" : { + "type" : "string" + }, + "nullableName" : { + "nullable" : true, + "type" : "string" + } + }, + "type" : "object" + }, + "Order" : { + "description" : "An order for a pets from the pet store", + "example" : { + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "petId" : { + "format" : "int64", + "type" : "integer" + }, + "quantity" : { + "format" : "int32", + "type" : "integer" + }, + "shipDate" : { + "format" : "date-time", + "type" : "string" + }, + "status" : { + "description" : "Order Status", + "enum" : [ "placed", "approved", "delivered" ], + "type" : "string" + }, + "complete" : { + "default" : false, + "type" : "boolean" + } + }, + "title" : "Pet Order", + "type" : "object", + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "description" : "A category for a pet", + "example" : { + "name" : "name", + "id" : 6 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", + "type" : "string" + } + }, + "title" : "Pet category", + "type" : "object", + "xml" : { + "name" : "Category" + } + }, + "User" : { + "description" : "A User who is purchasing from the pet store", + "example" : { + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "username" : { + "type" : "string" + }, + "firstName" : { + "type" : "string" + }, + "lastName" : { + "type" : "string" + }, + "email" : { + "type" : "string" + }, + "password" : { + "type" : "string" + }, + "phone" : { + "type" : "string" + }, + "userStatus" : { + "description" : "User Status", + "format" : "int32", + "type" : "integer" + } + }, + "title" : "a User", + "type" : "object", + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "description" : "A tag for a pet", + "example" : { + "name" : "name", + "id" : 1 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "type" : "object", + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "description" : "A pet for sale in the pet store", + "example" : { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "category" : { + "$ref" : "#/components/schemas/Category" + }, + "name" : { + "example" : "doggie", + "type" : "string" + }, + "photoUrls" : { + "items" : { + "type" : "string" + }, + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + } + }, + "tags" : { + "items" : { + "$ref" : "#/components/schemas/Tag" + }, + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + } + }, + "status" : { + "deprecated" : true, + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + } + }, + "required" : [ "name", "photoUrls" ], + "title" : "a Pet", + "type" : "object", + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "description" : "Describes the result of uploading an image resource", + "example" : { + "code" : 0, + "type" : "type", + "message" : "message" + }, + "properties" : { + "code" : { + "format" : "int32", + "type" : "integer" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "type" : "object" + }, + "Dog" : { + "allOf" : [ { + "$ref" : "#/components/schemas/Animal" + }, { + "properties" : { + "breed" : { + "type" : "string" + } + }, + "type" : "object" + } ] + }, + "Cat" : { + "allOf" : [ { + "$ref" : "#/components/schemas/Animal" + }, { + "properties" : { + "declawed" : { + "type" : "boolean" + } + }, + "type" : "object" + } ] + }, + "Animal" : { + "discriminator" : { + "mapping" : { + "DOG" : "#/components/schemas/Dog", + "CAT" : "#/components/schemas/Cat" + }, + "propertyName" : "className" + }, + "properties" : { + "className" : { + "type" : "string" + }, + "color" : { + "default" : "red", + "type" : "string" + } + }, + "required" : [ "className" ], + "type" : "object" + }, + "updatePetWithForm_request" : { + "properties" : { + "name" : { + "description" : "Updated name of the pet", + "type" : "string" + }, + "status" : { + "description" : "Updated status of the pet", + "type" : "string" + } + }, + "type" : "object" + }, + "uploadFile_request" : { + "properties" : { + "additionalMetadata" : { + "description" : "Additional data to pass to server", + "type" : "string" + }, + "file" : { + "description" : "file to upload", + "format" : "binary", + "type" : "string" + } + }, + "type" : "object" + } + }, + "securitySchemes" : { + "petstore_auth" : { + "flows" : { + "implicit" : { + "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", + "scopes" : { + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" + } + } + }, + "type" : "oauth2" + }, + "api_key" : { + "in" : "header", + "name" : "api_key", + "type" : "apiKey" + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json index e69de29bb2d1..b47dce3d2c68 100644 --- a/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json +++ b/samples/server/petstore/aspnetcore-8.0-project4Models/src/Org.OpenAPITools/wwwroot/openapi-original.json @@ -0,0 +1,1203 @@ +{ + "openapi" : "3.0.0", + "info" : { + "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", + "license" : { + "name" : "Apache-2.0", + "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "title" : "OpenAPI Petstore", + "version" : "1.0.0" + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + }, + "servers" : [ { + "url" : "http://petstore.swagger.io/v2" + } ], + "tags" : [ { + "description" : "Everything about your Pets", + "name" : "pet" + }, { + "description" : "Access to Petstore orders", + "name" : "store" + }, { + "description" : "Operations about user", + "name" : "user" + } ], + "paths" : { + "/test" : { + "get" : { + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "testQuery", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/TestEnum" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "description" : "OK" + } + }, + "summary" : "Test API" + } + }, + "/pet" : { + "post" : { + "description" : "", + "operationId" : "addPet", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Add a new pet to the store", + "tags" : [ "pet" ] + }, + "put" : { + "description" : "", + "operationId" : "updatePet", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + }, + "405" : { + "description" : "Validation exception" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Update an existing pet", + "tags" : [ "pet" ] + } + }, + "/pet/findByStatus" : { + "get" : { + "description" : "Multiple status values can be provided with comma separated strings", + "operationId" : "findPetsByStatus", + "parameters" : [ { + "deprecated" : true, + "description" : "Status values that need to be considered for filter", + "explode" : false, + "in" : "query", + "name" : "status", + "required" : true, + "schema" : { + "items" : { + "default" : "available", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid status value" + } + }, + "security" : [ { + "petstore_auth" : [ "read:pets" ] + } ], + "summary" : "Finds Pets by status", + "tags" : [ "pet" ] + } + }, + "/pet/findByTags" : { + "get" : { + "deprecated" : true, + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "parameters" : [ { + "description" : "Tags to filter by", + "explode" : false, + "in" : "query", + "name" : "tags", + "required" : true, + "schema" : { + "items" : { + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid tag value" + } + }, + "security" : [ { + "petstore_auth" : [ "read:pets" ] + } ], + "summary" : "Finds Pets by tags", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}" : { + "delete" : { + "description" : "", + "operationId" : "deletePet", + "parameters" : [ { + "explode" : false, + "in" : "header", + "name" : "api_key", + "required" : false, + "schema" : { + "type" : "string" + }, + "style" : "simple" + }, { + "description" : "Pet id to delete", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid pet value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Deletes a pet", + "tags" : [ "pet" ] + }, + "get" : { + "description" : "Returns a single pet", + "operationId" : "getPetById", + "parameters" : [ { + "description" : "ID of pet to return", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Find pet by ID", + "tags" : [ "pet" ] + }, + "post" : { + "description" : "", + "operationId" : "updatePetWithForm", + "parameters" : [ { + "description" : "ID of pet that needs to be updated", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "application/x-www-form-urlencoded" : { + "schema" : { + "$ref" : "#/components/schemas/updatePetWithForm_request" + } + } + } + }, + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Updates a pet in the store with form data", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "description" : "", + "operationId" : "uploadFile", + "parameters" : [ { + "description" : "ID of pet to update", + "explode" : false, + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "multipart/form-data" : { + "schema" : { + "$ref" : "#/components/schemas/uploadFile_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ApiResponse" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "uploads an image", + "tags" : [ "pet" ] + } + }, + "/store/inventory" : { + "get" : { + "description" : "Returns a map of status codes to quantities", + "operationId" : "getInventory", + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "additionalProperties" : { + "format" : "int32", + "type" : "integer" + }, + "type" : "object" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Returns pet inventories by status", + "tags" : [ "store" ] + } + }, + "/store/order" : { + "post" : { + "description" : "", + "operationId" : "placeOrder", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "order placed for purchasing the pet", + "required" : true + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid Order" + } + }, + "summary" : "Place an order for a pet", + "tags" : [ "store" ] + } + }, + "/store/order/{orderId}" : { + "delete" : { + "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId" : "deleteOrder", + "parameters" : [ { + "description" : "ID of the order that needs to be deleted", + "explode" : false, + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "summary" : "Delete purchase order by ID", + "tags" : [ "store" ] + }, + "get" : { + "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions", + "operationId" : "getOrderById", + "parameters" : [ { + "description" : "ID of pet that needs to be fetched", + "explode" : false, + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "format" : "int64", + "maximum" : 5, + "minimum" : 1, + "type" : "integer" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + }, + "summary" : "Find purchase order by ID", + "tags" : [ "store" ] + } + }, + "/user" : { + "post" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Created user object", + "required" : true + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Create user", + "tags" : [ "user" ] + } + }, + "/user/createWithArray" : { + "post" : { + "description" : "", + "operationId" : "createUsersWithArrayInput", + "requestBody" : { + "$ref" : "#/components/requestBodies/UserArray" + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ] + } + }, + "/user/createWithList" : { + "post" : { + "description" : "", + "operationId" : "createUsersWithListInput", + "requestBody" : { + "$ref" : "#/components/requestBodies/UserArray" + }, + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ] + } + }, + "/user/login" : { + "get" : { + "description" : "", + "operationId" : "loginUser", + "parameters" : [ { + "description" : "The user name for login", + "explode" : true, + "in" : "query", + "name" : "username", + "required" : true, + "schema" : { + "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", + "type" : "string" + }, + "style" : "form" + }, { + "description" : "The password for login in clear text", + "explode" : true, + "in" : "query", + "name" : "password", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "type" : "string" + } + }, + "application/json" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "successful operation", + "headers" : { + "Set-Cookie" : { + "description" : "Cookie authentication key for use with the `api_key` apiKey authentication.", + "explode" : false, + "schema" : { + "example" : "AUTH_KEY=abcde12345; Path=/; HttpOnly", + "type" : "string" + }, + "style" : "simple" + }, + "X-Rate-Limit" : { + "description" : "calls per hour allowed by the user", + "explode" : false, + "schema" : { + "format" : "int32", + "type" : "integer" + }, + "style" : "simple" + }, + "X-Expires-After" : { + "description" : "date in UTC when token expires", + "explode" : false, + "schema" : { + "format" : "date-time", + "type" : "string" + }, + "style" : "simple" + } + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + }, + "summary" : "Logs user into the system", + "tags" : [ "user" ] + } + }, + "/user/logout" : { + "get" : { + "description" : "", + "operationId" : "logoutUser", + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Logs out current logged in user session", + "tags" : [ "user" ] + } + }, + "/user/{username}" : { + "delete" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "parameters" : [ { + "description" : "The name that needs to be deleted", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Delete user", + "tags" : [ "user" ] + }, + "get" : { + "description" : "", + "operationId" : "getUserByName", + "parameters" : [ { + "description" : "The name that needs to be fetched. Use user1 for testing.", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "summary" : "Get user by user name", + "tags" : [ "user" ] + }, + "put" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "parameters" : [ { + "description" : "name that need to be deleted", + "explode" : false, + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + } ], + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Updated user object", + "required" : true + }, + "responses" : { + "400" : { + "description" : "Invalid user supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Updated user", + "tags" : [ "user" ] + } + }, + "/fake/parameter_example_test" : { + "get" : { + "description" : "", + "operationId" : "fake_parameter_example_test", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "data", + "required" : true, + "schema" : { + "$ref" : "#/components/schemas/Pet" + }, + "style" : "form" + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + }, + "summary" : "fake endpoint to test parameter example (object)", + "tags" : [ "fake" ] + } + }, + "/fake/nullable_example_test" : { + "get" : { + "description" : "", + "operationId" : "fake_nullable_example_test", + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/TestNullable" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Fake endpoint to test nullable example (object)", + "tags" : [ "fake" ] + } + } + }, + "components" : { + "requestBodies" : { + "UserArray" : { + "content" : { + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/User" + }, + "type" : "array" + } + } + }, + "description" : "List of user object", + "required" : true + }, + "Pet" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "Pet object that needs to be added to the store", + "required" : true + } + }, + "schemas" : { + "TestEnum" : { + "enum" : [ "A", "B" ], + "type" : "string" + }, + "TestNullable" : { + "example" : { + "nullableName" : "nullableName", + "name" : "name" + }, + "properties" : { + "name" : { + "type" : "string" + }, + "nullableName" : { + "nullable" : true, + "type" : "string" + } + }, + "type" : "object" + }, + "Order" : { + "description" : "An order for a pets from the pet store", + "example" : { + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "petId" : { + "format" : "int64", + "type" : "integer" + }, + "quantity" : { + "format" : "int32", + "type" : "integer" + }, + "shipDate" : { + "format" : "date-time", + "type" : "string" + }, + "status" : { + "description" : "Order Status", + "enum" : [ "placed", "approved", "delivered" ], + "type" : "string" + }, + "complete" : { + "default" : false, + "type" : "boolean" + } + }, + "title" : "Pet Order", + "type" : "object", + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "description" : "A category for a pet", + "example" : { + "name" : "name", + "id" : 6 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "pattern" : "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", + "type" : "string" + } + }, + "title" : "Pet category", + "type" : "object", + "xml" : { + "name" : "Category" + } + }, + "User" : { + "description" : "A User who is purchasing from the pet store", + "example" : { + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "username" : { + "type" : "string" + }, + "firstName" : { + "type" : "string" + }, + "lastName" : { + "type" : "string" + }, + "email" : { + "type" : "string" + }, + "password" : { + "type" : "string" + }, + "phone" : { + "type" : "string" + }, + "userStatus" : { + "description" : "User Status", + "format" : "int32", + "type" : "integer" + } + }, + "title" : "a User", + "type" : "object", + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "description" : "A tag for a pet", + "example" : { + "name" : "name", + "id" : 1 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "type" : "object", + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "description" : "A pet for sale in the pet store", + "example" : { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "category" : { + "$ref" : "#/components/schemas/Category" + }, + "name" : { + "example" : "doggie", + "type" : "string" + }, + "photoUrls" : { + "items" : { + "type" : "string" + }, + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + } + }, + "tags" : { + "items" : { + "$ref" : "#/components/schemas/Tag" + }, + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + } + }, + "status" : { + "deprecated" : true, + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + } + }, + "required" : [ "name", "photoUrls" ], + "title" : "a Pet", + "type" : "object", + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "description" : "Describes the result of uploading an image resource", + "example" : { + "code" : 0, + "type" : "type", + "message" : "message" + }, + "properties" : { + "code" : { + "format" : "int32", + "type" : "integer" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "type" : "object" + }, + "Dog" : { + "allOf" : [ { + "$ref" : "#/components/schemas/Animal" + }, { + "properties" : { + "breed" : { + "type" : "string" + } + }, + "type" : "object" + } ] + }, + "Cat" : { + "allOf" : [ { + "$ref" : "#/components/schemas/Animal" + }, { + "properties" : { + "declawed" : { + "type" : "boolean" + } + }, + "type" : "object" + } ] + }, + "Animal" : { + "discriminator" : { + "mapping" : { + "DOG" : "#/components/schemas/Dog", + "CAT" : "#/components/schemas/Cat" + }, + "propertyName" : "className" + }, + "properties" : { + "className" : { + "type" : "string" + }, + "color" : { + "default" : "red", + "type" : "string" + } + }, + "required" : [ "className" ], + "type" : "object" + }, + "updatePetWithForm_request" : { + "properties" : { + "name" : { + "description" : "Updated name of the pet", + "type" : "string" + }, + "status" : { + "description" : "Updated status of the pet", + "type" : "string" + } + }, + "type" : "object" + }, + "uploadFile_request" : { + "properties" : { + "additionalMetadata" : { + "description" : "Additional data to pass to server", + "type" : "string" + }, + "file" : { + "description" : "file to upload", + "format" : "binary", + "type" : "string" + } + }, + "type" : "object" + } + }, + "securitySchemes" : { + "petstore_auth" : { + "flows" : { + "implicit" : { + "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", + "scopes" : { + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" + } + } + }, + "type" : "oauth2" + }, + "api_key" : { + "in" : "header", + "name" : "api_key", + "type" : "apiKey" + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-8.0-use-centralized-package-version-management/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/.openapi-generator/VERSION index 909dcd0eca63..193a12d6e891 100644 --- a/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-8.0-useSwashBuckle/.openapi-generator/VERSION @@ -1 +1 @@ -7.19.0-SNAPSHOT +7.20.0-SNAPSHOT diff --git a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs index e69de29bb2d1..9eccd5c317f6 100644 --- a/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs +++ b/samples/server/petstore/aspnetcore-8.0/src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs @@ -0,0 +1,107 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +using System.ComponentModel.DataAnnotations; +using System.Linq; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Org.OpenAPITools.Filters +{ + /// + /// Path Parameter Validation Rules Filter + /// + public class GeneratePathParamsValidationFilter : IOperationFilter + { + /// + /// Constructor + /// + /// Operation + /// OperationFilterContext + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + var pars = context.ApiDescription.ParameterDescriptions; + + foreach (var par in pars) + { + var openapiParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name); + + var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes.ToList(); + + // See https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1147 + // and https://mikeralphson.github.io/openapi/2017/03/15/openapi3.0.0-rc0 + // Basically OpenAPI v3 body parameters are split out into RequestBody and the properties have moved to schema + if (attributes.Any() && openapiParam != null) + { + // Required - [Required] + var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute)); + if (requiredAttr != null) + { + openapiParam.Required = true; + } + + // Regex Pattern [RegularExpression] + var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute)); + if (regexAttr != null) + { + var regex = (string)regexAttr.ConstructorArguments[0].Value; + openapiParam.Schema.Pattern = regex; + } + + // String Length [StringLength] + int? minLength = null, maxLength = null; + var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute)); + if (stringLengthAttr != null) + { + if (stringLengthAttr.NamedArguments.Count == 1) + { + minLength = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value; + } + maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value; + } + + var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute)); + if (minLengthAttr != null) + { + minLength = (int)minLengthAttr.ConstructorArguments[0].Value; + } + + var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute)); + if (maxLengthAttr != null) + { + maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value; + } + + if (minLength != null) + { + openapiParam.Schema.MinLength = minLength; + } + + if (maxLength != null) + { + openapiParam.Schema.MaxLength = maxLength; + } + + // Range [Range] + var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute)); + if (rangeAttr != null) + { + var rangeMin = (int)rangeAttr.ConstructorArguments[0].Value; + var rangeMax = (int)rangeAttr.ConstructorArguments[1].Value; + + openapiParam.Schema.MinLength = rangeMin; + openapiParam.Schema.MaxLength = rangeMax; + } + } + } + } + } +} diff --git a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/wwwroot/openapi-original.json b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/wwwroot/openapi-original.json index e69de29bb2d1..333dcf2bfceb 100644 --- a/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/wwwroot/openapi-original.json +++ b/samples/server/petstore/aspnetcore/src/Org.OpenAPITools/wwwroot/openapi-original.json @@ -0,0 +1,1021 @@ +{ + "openapi" : "3.0.1", + "info" : { + "description" : "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.", + "license" : { + "name" : "Apache-2.0", + "url" : "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "title" : "OpenAPI Petstore", + "version" : "1.0.0" + }, + "servers" : [ { + "url" : "http://petstore.swagger.io/v2" + } ], + "tags" : [ { + "description" : "Everything about your Pets", + "name" : "pet" + }, { + "description" : "Access to Petstore orders", + "name" : "store" + }, { + "description" : "Operations about user", + "name" : "user" + } ], + "paths" : { + "/pet" : { + "post" : { + "operationId" : "addPet", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "Pet object that needs to be added to the store", + "required" : true + }, + "responses" : { + "405" : { + "content" : { }, + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Add a new pet to the store", + "tags" : [ "pet" ], + "x-codegen-request-body-name" : "body" + }, + "put" : { + "operationId" : "updatePet", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "Pet object that needs to be added to the store", + "required" : true + }, + "responses" : { + "400" : { + "content" : { }, + "description" : "Invalid ID supplied" + }, + "404" : { + "content" : { }, + "description" : "Pet not found" + }, + "405" : { + "content" : { }, + "description" : "Validation exception" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Update an existing pet", + "tags" : [ "pet" ], + "x-codegen-request-body-name" : "body" + } + }, + "/pet/findByStatus" : { + "get" : { + "description" : "Multiple status values can be provided with comma separated strings", + "operationId" : "findPetsByStatus", + "parameters" : [ { + "description" : "Status values that need to be considered for filter", + "explode" : false, + "in" : "query", + "name" : "status", + "required" : true, + "schema" : { + "items" : { + "default" : "available", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "content" : { }, + "description" : "Invalid status value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Finds Pets by status", + "tags" : [ "pet" ] + } + }, + "/pet/findByTags" : { + "get" : { + "deprecated" : true, + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "parameters" : [ { + "description" : "Tags to filter by", + "explode" : false, + "in" : "query", + "name" : "tags", + "required" : true, + "schema" : { + "items" : { + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + }, + "application/json" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/Pet" + }, + "type" : "array" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "content" : { }, + "description" : "Invalid tag value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Finds Pets by tags", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}" : { + "delete" : { + "operationId" : "deletePet", + "parameters" : [ { + "in" : "header", + "name" : "api_key", + "schema" : { + "type" : "string" + } + }, { + "description" : "Pet id to delete", + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + } + } ], + "responses" : { + "400" : { + "content" : { }, + "description" : "Invalid pet value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Deletes a pet", + "tags" : [ "pet" ] + }, + "get" : { + "description" : "Returns a single pet", + "operationId" : "getPetById", + "parameters" : [ { + "description" : "ID of pet to return", + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + } + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "content" : { }, + "description" : "Invalid ID supplied" + }, + "404" : { + "content" : { }, + "description" : "Pet not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Find pet by ID", + "tags" : [ "pet" ] + }, + "post" : { + "operationId" : "updatePetWithForm", + "parameters" : [ { + "description" : "ID of pet that needs to be updated", + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + } + } ], + "requestBody" : { + "content" : { + "application/x-www-form-urlencoded" : { + "schema" : { + "$ref" : "#/components/schemas/updatePetWithForm_request" + } + } + } + }, + "responses" : { + "405" : { + "content" : { }, + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "Updates a pet in the store with form data", + "tags" : [ "pet" ] + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "operationId" : "uploadFile", + "parameters" : [ { + "description" : "ID of pet to update", + "in" : "path", + "name" : "petId", + "required" : true, + "schema" : { + "format" : "int64", + "type" : "integer" + } + } ], + "requestBody" : { + "content" : { + "multipart/form-data" : { + "schema" : { + "$ref" : "#/components/schemas/uploadFile_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/ApiResponse" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ], + "summary" : "uploads an image", + "tags" : [ "pet" ] + } + }, + "/store/inventory" : { + "get" : { + "description" : "Returns a map of status codes to quantities", + "operationId" : "getInventory", + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "additionalProperties" : { + "format" : "int32", + "type" : "integer" + }, + "type" : "object" + } + } + }, + "description" : "successful operation" + } + }, + "security" : [ { + "api_key" : [ ] + } ], + "summary" : "Returns pet inventories by status", + "tags" : [ "store" ] + } + }, + "/store/order" : { + "post" : { + "operationId" : "placeOrder", + "requestBody" : { + "content" : { + "*/*" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "order placed for purchasing the pet", + "required" : true + }, + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "content" : { }, + "description" : "Invalid Order" + } + }, + "summary" : "Place an order for a pet", + "tags" : [ "store" ], + "x-codegen-request-body-name" : "body" + } + }, + "/store/order/{orderId}" : { + "delete" : { + "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId" : "deleteOrder", + "parameters" : [ { + "description" : "ID of the order that needs to be deleted", + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "responses" : { + "400" : { + "content" : { }, + "description" : "Invalid ID supplied" + }, + "404" : { + "content" : { }, + "description" : "Order not found" + } + }, + "summary" : "Delete purchase order by ID", + "tags" : [ "store" ] + }, + "get" : { + "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions", + "operationId" : "getOrderById", + "parameters" : [ { + "description" : "ID of pet that needs to be fetched", + "in" : "path", + "name" : "orderId", + "required" : true, + "schema" : { + "format" : "int64", + "maximum" : 5, + "minimum" : 1, + "type" : "integer" + } + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Order" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "content" : { }, + "description" : "Invalid ID supplied" + }, + "404" : { + "content" : { }, + "description" : "Order not found" + } + }, + "summary" : "Find purchase order by ID", + "tags" : [ "store" ] + } + }, + "/user" : { + "post" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "requestBody" : { + "content" : { + "*/*" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Created user object", + "required" : true + }, + "responses" : { + "default" : { + "content" : { }, + "description" : "successful operation" + } + }, + "summary" : "Create user", + "tags" : [ "user" ], + "x-codegen-request-body-name" : "body" + } + }, + "/user/createWithArray" : { + "post" : { + "operationId" : "createUsersWithArrayInput", + "requestBody" : { + "content" : { + "*/*" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/User" + }, + "type" : "array" + } + } + }, + "description" : "List of user object", + "required" : true + }, + "responses" : { + "default" : { + "content" : { }, + "description" : "successful operation" + } + }, + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ], + "x-codegen-request-body-name" : "body" + } + }, + "/user/createWithList" : { + "post" : { + "operationId" : "createUsersWithListInput", + "requestBody" : { + "content" : { + "*/*" : { + "schema" : { + "items" : { + "$ref" : "#/components/schemas/User" + }, + "type" : "array" + } + } + }, + "description" : "List of user object", + "required" : true + }, + "responses" : { + "default" : { + "content" : { }, + "description" : "successful operation" + } + }, + "summary" : "Creates list of users with given input array", + "tags" : [ "user" ], + "x-codegen-request-body-name" : "body" + } + }, + "/user/login" : { + "get" : { + "operationId" : "loginUser", + "parameters" : [ { + "description" : "The user name for login", + "in" : "query", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + } + }, { + "description" : "The password for login in clear text", + "in" : "query", + "name" : "password", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "type" : "string" + } + }, + "application/json" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "successful operation", + "headers" : { + "X-Rate-Limit" : { + "description" : "calls per hour allowed by the user", + "schema" : { + "format" : "int32", + "type" : "integer" + } + }, + "X-Expires-After" : { + "description" : "date in UTC when token expires", + "schema" : { + "format" : "date-time", + "type" : "string" + } + } + } + }, + "400" : { + "content" : { }, + "description" : "Invalid username/password supplied" + } + }, + "summary" : "Logs user into the system", + "tags" : [ "user" ] + } + }, + "/user/logout" : { + "get" : { + "operationId" : "logoutUser", + "responses" : { + "default" : { + "content" : { }, + "description" : "successful operation" + } + }, + "summary" : "Logs out current logged in user session", + "tags" : [ "user" ] + } + }, + "/user/{username}" : { + "delete" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "parameters" : [ { + "description" : "The name that needs to be deleted", + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "responses" : { + "400" : { + "content" : { }, + "description" : "Invalid username supplied" + }, + "404" : { + "content" : { }, + "description" : "User not found" + } + }, + "summary" : "Delete user", + "tags" : [ "user" ] + }, + "get" : { + "operationId" : "getUserByName", + "parameters" : [ { + "description" : "The name that needs to be fetched. Use user1 for testing.", + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "responses" : { + "200" : { + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "successful operation" + }, + "400" : { + "content" : { }, + "description" : "Invalid username supplied" + }, + "404" : { + "content" : { }, + "description" : "User not found" + } + }, + "summary" : "Get user by user name", + "tags" : [ "user" ] + }, + "put" : { + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "parameters" : [ { + "description" : "name that need to be deleted", + "in" : "path", + "name" : "username", + "required" : true, + "schema" : { + "type" : "string" + } + } ], + "requestBody" : { + "content" : { + "*/*" : { + "schema" : { + "$ref" : "#/components/schemas/User" + } + } + }, + "description" : "Updated user object", + "required" : true + }, + "responses" : { + "400" : { + "content" : { }, + "description" : "Invalid user supplied" + }, + "404" : { + "content" : { }, + "description" : "User not found" + } + }, + "summary" : "Updated user", + "tags" : [ "user" ], + "x-codegen-request-body-name" : "body" + } + } + }, + "components" : { + "schemas" : { + "Order" : { + "description" : "An order for a pets from the pet store", + "example" : { + "petId" : 6, + "quantity" : 1, + "id" : 0, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : false, + "status" : "placed" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "petId" : { + "format" : "int64", + "type" : "integer" + }, + "quantity" : { + "format" : "int32", + "type" : "integer" + }, + "shipDate" : { + "format" : "date-time", + "type" : "string" + }, + "status" : { + "description" : "Order Status", + "enum" : [ "placed", "approved", "delivered" ], + "type" : "string" + }, + "complete" : { + "default" : false, + "type" : "boolean" + } + }, + "title" : "Pet Order", + "type" : "object", + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "description" : "A category for a pet", + "example" : { + "name" : "name", + "id" : 6 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet category", + "type" : "object", + "xml" : { + "name" : "Category" + } + }, + "User" : { + "description" : "A User who is purchasing from the pet store", + "example" : { + "firstName" : "firstName", + "lastName" : "lastName", + "password" : "password", + "userStatus" : 6, + "phone" : "phone", + "id" : 0, + "email" : "email", + "username" : "username" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "username" : { + "type" : "string" + }, + "firstName" : { + "type" : "string" + }, + "lastName" : { + "type" : "string" + }, + "email" : { + "type" : "string" + }, + "password" : { + "type" : "string" + }, + "phone" : { + "type" : "string" + }, + "userStatus" : { + "description" : "User Status", + "format" : "int32", + "type" : "integer" + } + }, + "title" : "a User", + "type" : "object", + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "description" : "A tag for a pet", + "example" : { + "name" : "name", + "id" : 1 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "type" : "object", + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "description" : "A pet for sale in the pet store", + "example" : { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 0, + "category" : { + "name" : "name", + "id" : 6 + }, + "tags" : [ { + "name" : "name", + "id" : 1 + }, { + "name" : "name", + "id" : 1 + } ], + "status" : "available" + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "category" : { + "$ref" : "#/components/schemas/Category" + }, + "name" : { + "example" : "doggie", + "type" : "string" + }, + "photoUrls" : { + "items" : { + "type" : "string" + }, + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + } + }, + "tags" : { + "items" : { + "$ref" : "#/components/schemas/Tag" + }, + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + } + }, + "status" : { + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + } + }, + "required" : [ "name", "photoUrls" ], + "title" : "a Pet", + "type" : "object", + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "description" : "Describes the result of uploading an image resource", + "example" : { + "code" : 0, + "type" : "type", + "message" : "message" + }, + "properties" : { + "code" : { + "format" : "int32", + "type" : "integer" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "type" : "object" + }, + "updatePetWithForm_request" : { + "properties" : { + "name" : { + "description" : "Updated name of the pet", + "type" : "string" + }, + "status" : { + "description" : "Updated status of the pet", + "type" : "string" + } + }, + "type" : "object" + }, + "uploadFile_request" : { + "properties" : { + "additionalMetadata" : { + "description" : "Additional data to pass to server", + "type" : "string" + }, + "file" : { + "description" : "file to upload", + "format" : "binary", + "type" : "string" + } + }, + "type" : "object" + } + }, + "securitySchemes" : { + "petstore_auth" : { + "flows" : { + "implicit" : { + "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", + "scopes" : { + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" + } + } + }, + "type" : "oauth2" + }, + "api_key" : { + "in" : "header", + "name" : "api_key", + "type" : "apiKey" + } + } + }, + "x-original-swagger-version" : "2.0" +} diff --git a/samples/server/petstore/cpp-oatpp/model/Order.hpp b/samples/server/petstore/cpp-oatpp/model/Order.hpp index e69de29bb2d1..3f69abb6a203 100644 --- a/samples/server/petstore/cpp-oatpp/model/Order.hpp +++ b/samples/server/petstore/cpp-oatpp/model/Order.hpp @@ -0,0 +1,59 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +/* + * Order.h + * + * An order for a pets from the pet store + */ + +#ifndef Order_H_ +#define Order_H_ + + +#include "oatpp/core/macro/codegen.hpp" +#include "oatpp/core/Types.hpp" + +namespace org::openapitools::server::model +{ + +/* Begin DTO code-generation */ +#include OATPP_CODEGEN_BEGIN(DTO) + +/** + * Message Data-Transfer-Object + */ +class Order : public oatpp::DTO { + + DTO_INIT(Order, DTO /* Extends */) + + DTO_FIELD(oatpp::Int64, id); + DTO_FIELD(oatpp::Boolean, idIsSet); + DTO_FIELD(oatpp::Int64, petId); + DTO_FIELD(oatpp::Boolean, petIdIsSet); + DTO_FIELD(oatpp::Int32, quantity); + DTO_FIELD(oatpp::Boolean, quantityIsSet); + DTO_FIELD(oatpp::String, shipDate); + DTO_FIELD(oatpp::Boolean, shipDateIsSet); + DTO_FIELD(oatpp::String, status); + DTO_FIELD(oatpp::Boolean, statusIsSet); + DTO_FIELD(oatpp::Boolean, complete); + DTO_FIELD(oatpp::Boolean, completeIsSet); + +}; + +/* End DTO code-generation */ +#include OATPP_CODEGEN_END(DTO) + + +} // namespace org::openapitools::server::model + +#endif /* Order_H_ */ diff --git a/samples/server/petstore/cpp-oatpp/model/Tag.hpp b/samples/server/petstore/cpp-oatpp/model/Tag.hpp index e69de29bb2d1..f7941e8e3911 100644 --- a/samples/server/petstore/cpp-oatpp/model/Tag.hpp +++ b/samples/server/petstore/cpp-oatpp/model/Tag.hpp @@ -0,0 +1,51 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +/* + * Tag.h + * + * A tag for a pet + */ + +#ifndef Tag_H_ +#define Tag_H_ + + +#include "oatpp/core/macro/codegen.hpp" +#include "oatpp/core/Types.hpp" + +namespace org::openapitools::server::model +{ + +/* Begin DTO code-generation */ +#include OATPP_CODEGEN_BEGIN(DTO) + +/** + * Message Data-Transfer-Object + */ +class Tag : public oatpp::DTO { + + DTO_INIT(Tag, DTO /* Extends */) + + DTO_FIELD(oatpp::Int64, id); + DTO_FIELD(oatpp::Boolean, idIsSet); + DTO_FIELD(oatpp::String, name); + DTO_FIELD(oatpp::Boolean, nameIsSet); + +}; + +/* End DTO code-generation */ +#include OATPP_CODEGEN_END(DTO) + + +} // namespace org::openapitools::server::model + +#endif /* Tag_H_ */ diff --git a/samples/server/petstore/cpp-pistache-everything/model/Order.cpp b/samples/server/petstore/cpp-pistache-everything/model/Order.cpp index e69de29bb2d1..459d6ee5d69a 100644 --- a/samples/server/petstore/cpp-pistache-everything/model/Order.cpp +++ b/samples/server/petstore/cpp-pistache-everything/model/Order.cpp @@ -0,0 +1,251 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + + +#include "Order.h" +#include "Helpers.h" + +#include + +namespace org::openapitools::server::model +{ + +Order::Order() +{ + m_Id = 0L; + m_IdIsSet = false; + m_PetId = 0L; + m_PetIdIsSet = false; + m_Quantity = 0; + m_QuantityIsSet = false; + m_ShipDate = ""; + m_ShipDateIsSet = false; + m_Status = ""; + m_StatusIsSet = false; + m_Complete = false; + m_CompleteIsSet = false; + +} + +void Order::validate() const +{ + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } +} + +bool Order::validate(std::stringstream& msg) const +{ + return validate(msg, ""); +} + +bool Order::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Order" : pathPrefix; + + + return success; +} + +bool Order::operator==(const Order& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!petIdIsSet() && !rhs.petIdIsSet()) || (petIdIsSet() && rhs.petIdIsSet() && getPetId() == rhs.getPetId())) && + + + ((!quantityIsSet() && !rhs.quantityIsSet()) || (quantityIsSet() && rhs.quantityIsSet() && getQuantity() == rhs.getQuantity())) && + + + ((!shipDateIsSet() && !rhs.shipDateIsSet()) || (shipDateIsSet() && rhs.shipDateIsSet() && getShipDate() == rhs.getShipDate())) && + + + ((!statusIsSet() && !rhs.statusIsSet()) || (statusIsSet() && rhs.statusIsSet() && getStatus() == rhs.getStatus())) && + + + ((!completeIsSet() && !rhs.completeIsSet()) || (completeIsSet() && rhs.completeIsSet() && isComplete() == rhs.isComplete())) + + ; +} + +bool Order::operator!=(const Order& rhs) const +{ + return !(*this == rhs); +} + +void to_json(nlohmann::json& j, const Order& o) +{ + j = nlohmann::json::object(); + if(o.idIsSet()) + j["id"] = o.m_Id; + if(o.petIdIsSet()) + j["petId"] = o.m_PetId; + if(o.quantityIsSet()) + j["quantity"] = o.m_Quantity; + if(o.shipDateIsSet()) + j["shipDate"] = o.m_ShipDate; + if(o.statusIsSet()) + j["status"] = o.m_Status; + if(o.completeIsSet()) + j["complete"] = o.m_Complete; + +} + +void from_json(const nlohmann::json& j, Order& o) +{ + if(j.find("id") != j.end()) + { + j.at("id").get_to(o.m_Id); + o.m_IdIsSet = true; + } + if(j.find("petId") != j.end()) + { + j.at("petId").get_to(o.m_PetId); + o.m_PetIdIsSet = true; + } + if(j.find("quantity") != j.end()) + { + j.at("quantity").get_to(o.m_Quantity); + o.m_QuantityIsSet = true; + } + if(j.find("shipDate") != j.end()) + { + j.at("shipDate").get_to(o.m_ShipDate); + o.m_ShipDateIsSet = true; + } + if(j.find("status") != j.end()) + { + j.at("status").get_to(o.m_Status); + o.m_StatusIsSet = true; + } + if(j.find("complete") != j.end()) + { + j.at("complete").get_to(o.m_Complete); + o.m_CompleteIsSet = true; + } + +} + +int64_t Order::getId() const +{ + return m_Id; +} +void Order::setId(int64_t const value) +{ + m_Id = value; + m_IdIsSet = true; +} +bool Order::idIsSet() const +{ + return m_IdIsSet; +} +void Order::unsetId() +{ + m_IdIsSet = false; +} +int64_t Order::getPetId() const +{ + return m_PetId; +} +void Order::setPetId(int64_t const value) +{ + m_PetId = value; + m_PetIdIsSet = true; +} +bool Order::petIdIsSet() const +{ + return m_PetIdIsSet; +} +void Order::unsetPetId() +{ + m_PetIdIsSet = false; +} +int32_t Order::getQuantity() const +{ + return m_Quantity; +} +void Order::setQuantity(int32_t const value) +{ + m_Quantity = value; + m_QuantityIsSet = true; +} +bool Order::quantityIsSet() const +{ + return m_QuantityIsSet; +} +void Order::unsetQuantity() +{ + m_QuantityIsSet = false; +} +std::string Order::getShipDate() const +{ + return m_ShipDate; +} +void Order::setShipDate(std::string const& value) +{ + m_ShipDate = value; + m_ShipDateIsSet = true; +} +bool Order::shipDateIsSet() const +{ + return m_ShipDateIsSet; +} +void Order::unsetShipDate() +{ + m_ShipDateIsSet = false; +} +std::string Order::getStatus() const +{ + return m_Status; +} +void Order::setStatus(std::string const& value) +{ + m_Status = value; + m_StatusIsSet = true; +} +bool Order::statusIsSet() const +{ + return m_StatusIsSet; +} +void Order::unsetStatus() +{ + m_StatusIsSet = false; +} +bool Order::isComplete() const +{ + return m_Complete; +} +void Order::setComplete(bool const value) +{ + m_Complete = value; + m_CompleteIsSet = true; +} +bool Order::completeIsSet() const +{ + return m_CompleteIsSet; +} +void Order::unsetComplete() +{ + m_CompleteIsSet = false; +} + + +} // namespace org::openapitools::server::model + diff --git a/samples/server/petstore/cpp-pistache-nested-schema-refs/api/StoreApi.cpp b/samples/server/petstore/cpp-pistache-nested-schema-refs/api/StoreApi.cpp index e69de29bb2d1..d23f51da8fd2 100644 --- a/samples/server/petstore/cpp-pistache-nested-schema-refs/api/StoreApi.cpp +++ b/samples/server/petstore/cpp-pistache-nested-schema-refs/api/StoreApi.cpp @@ -0,0 +1,103 @@ +/** +* Test swagger file +* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + +#include "StoreApi.h" +#include "Helpers.h" + +namespace org::openapitools::server::api +{ + +using namespace org::openapitools::server::helpers; +using namespace org::openapitools::server::model; + +const std::string StoreApi::base = ""; + +StoreApi::StoreApi(const std::shared_ptr& rtr) + : ApiBase(rtr) +{} + +void StoreApi::init() { + setupRoutes(); +} + +void StoreApi::setupRoutes() { + using namespace Pistache::Rest; + + Routes::Get(*router, base + "/pet", Routes::bind(&StoreApi::get_nested_object_handler, this)); + + // Default handler, called when a route is not found + router->addCustomHandler(Routes::bind(&StoreApi::store_api_default_handler, this)); +} + +void StoreApi::handleParsingException(const std::exception& ex, Pistache::Http::ResponseWriter &response) const noexcept { + std::pair codeAndError = handleParsingException(ex); + response.send(codeAndError.first, codeAndError.second); +} + +std::pair StoreApi::handleParsingException(const std::exception& ex) const noexcept { + try { + throw; + } catch (nlohmann::detail::exception &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (org::openapitools::server::helpers::ValidationException &e) { + return std::make_pair(Pistache::Http::Code::Bad_Request, e.what()); + } catch (std::exception &e) { + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, e.what()); + } +} + +void StoreApi::handleOperationException(const std::exception& ex, Pistache::Http::ResponseWriter &response) const noexcept { + std::pair codeAndError = handleOperationException(ex); + response.send(codeAndError.first, codeAndError.second); +} + +std::pair StoreApi::handleOperationException(const std::exception& ex) const noexcept { + return std::make_pair(Pistache::Http::Code::Internal_Server_Error, ex.what()); +} + +void StoreApi::get_nested_object_handler(const Pistache::Rest::Request& request, Pistache::Http::ResponseWriter response) { + try { + + + + + + + try { + + + + + + this->get_nested_object(response); + } catch (Pistache::Http::HttpError &e) { + response.send(static_cast(e.code()), e.what()); + return; + } catch (std::exception &e) { + this->handleOperationException(e, response); + return; + } + + } catch (std::exception &e) { + response.send(Pistache::Http::Code::Internal_Server_Error, e.what()); + } + + +} + + +void StoreApi::store_api_default_handler(const Pistache::Rest::Request &, Pistache::Http::ResponseWriter response) { + response.send(Pistache::Http::Code::Not_Found, "The requested method does not exist"); +} + +} // namespace org::openapitools::server::api + diff --git a/samples/server/petstore/cpp-pistache/model/Category.cpp b/samples/server/petstore/cpp-pistache/model/Category.cpp index e69de29bb2d1..489c22157ada 100644 --- a/samples/server/petstore/cpp-pistache/model/Category.cpp +++ b/samples/server/petstore/cpp-pistache/model/Category.cpp @@ -0,0 +1,135 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ + + +#include "Category.h" +#include "Helpers.h" + +#include + +namespace org::openapitools::server::model +{ + +Category::Category() +{ + m_Id = 0L; + m_IdIsSet = false; + m_Name = ""; + m_NameIsSet = false; + +} + +void Category::validate() const +{ + std::stringstream msg; + if (!validate(msg)) + { + throw org::openapitools::server::helpers::ValidationException(msg.str()); + } +} + +bool Category::validate(std::stringstream& msg) const +{ + return validate(msg, ""); +} + +bool Category::validate(std::stringstream& msg, const std::string& pathPrefix) const +{ + bool success = true; + const std::string _pathPrefix = pathPrefix.empty() ? "Category" : pathPrefix; + + + return success; +} + +bool Category::operator==(const Category& rhs) const +{ + return + + + + ((!idIsSet() && !rhs.idIsSet()) || (idIsSet() && rhs.idIsSet() && getId() == rhs.getId())) && + + + ((!nameIsSet() && !rhs.nameIsSet()) || (nameIsSet() && rhs.nameIsSet() && getName() == rhs.getName())) + + ; +} + +bool Category::operator!=(const Category& rhs) const +{ + return !(*this == rhs); +} + +void to_json(nlohmann::json& j, const Category& o) +{ + j = nlohmann::json::object(); + if(o.idIsSet()) + j["id"] = o.m_Id; + if(o.nameIsSet()) + j["name"] = o.m_Name; + +} + +void from_json(const nlohmann::json& j, Category& o) +{ + if(j.find("id") != j.end()) + { + j.at("id").get_to(o.m_Id); + o.m_IdIsSet = true; + } + if(j.find("name") != j.end()) + { + j.at("name").get_to(o.m_Name); + o.m_NameIsSet = true; + } + +} + +int64_t Category::getId() const +{ + return m_Id; +} +void Category::setId(int64_t const value) +{ + m_Id = value; + m_IdIsSet = true; +} +bool Category::idIsSet() const +{ + return m_IdIsSet; +} +void Category::unsetId() +{ + m_IdIsSet = false; +} +std::string Category::getName() const +{ + return m_Name; +} +void Category::setName(std::string const& value) +{ + m_Name = value; + m_NameIsSet = true; +} +bool Category::nameIsSet() const +{ + return m_NameIsSet; +} +void Category::unsetName() +{ + m_NameIsSet = false; +} + + +} // namespace org::openapitools::server::model + From e8368a968395e7cbfc10040adb77226851bfe6a0 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Fri, 13 Feb 2026 15:23:08 +0800 Subject: [PATCH 5/5] update doc --- docs/generators/crystal.md | 4 +++- docs/generators/groovy.md | 2 ++ docs/generators/java-camel.md | 6 +++++- docs/generators/java-dubbo.md | 2 ++ docs/generators/java-helidon-client.md | 2 ++ docs/generators/java-helidon-server.md | 2 ++ docs/generators/java-inflector.md | 2 ++ docs/generators/java-micronaut-client.md | 2 ++ docs/generators/java-micronaut-server.md | 2 ++ docs/generators/java-microprofile.md | 2 ++ docs/generators/java-msf4j.md | 2 ++ docs/generators/java-pkmst.md | 2 ++ docs/generators/java-play-framework.md | 2 ++ docs/generators/java-undertow-server.md | 2 ++ docs/generators/java-vertx-web.md | 2 ++ docs/generators/java-vertx.md | 2 ++ docs/generators/java-wiremock.md | 2 ++ docs/generators/java.md | 2 ++ docs/generators/jaxrs-cxf-cdi.md | 2 ++ docs/generators/jaxrs-cxf-client.md | 2 ++ docs/generators/jaxrs-cxf-extended.md | 2 ++ docs/generators/jaxrs-cxf.md | 2 ++ docs/generators/jaxrs-jersey.md | 2 ++ docs/generators/jaxrs-resteasy-eap.md | 2 ++ docs/generators/jaxrs-resteasy.md | 2 ++ docs/generators/jaxrs-spec.md | 2 ++ docs/generators/kotlin-server.md | 7 ++++--- docs/generators/kotlin-spring.md | 6 +++++- docs/generators/protobuf-schema.md | 1 + docs/generators/python-fastapi.md | 2 +- docs/generators/spring.md | 6 +++++- docs/generators/swift5.md | 2 +- docs/generators/typescript-angular.md | 4 ++-- docs/generators/typescript-axios.md | 2 +- docs/generators/typescript.md | 1 + 35 files changed, 77 insertions(+), 12 deletions(-) diff --git a/docs/generators/crystal.md b/docs/generators/crystal.md index ba481b67e4da..ea2b3cc400db 100644 --- a/docs/generators/crystal.md +++ b/docs/generators/crystal.md @@ -94,7 +94,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • if
  • in
  • include
  • -
  • instance
  • +
  • instance_sizeof
  • is_a?
  • lib
  • macro
  • @@ -102,9 +102,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • next
  • nil
  • nil?
  • +
  • object_id
  • of
  • out
  • pointerof
  • +
  • previous_def
  • private
  • protected
  • require
  • diff --git a/docs/generators/groovy.md b/docs/generators/groovy.md index e2f1314c4bb1..d5cdff849435 100644 --- a/docs/generators/groovy.md +++ b/docs/generators/groovy.md @@ -30,10 +30,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-camel.md b/docs/generators/java-camel.md index b50d9b4728c1..0651cc84e31d 100644 --- a/docs/generators/java-camel.md +++ b/docs/generators/java-camel.md @@ -44,11 +44,13 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configPackage|configuration package for generated code| |org.openapitools.configuration| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |delegatePattern|Whether to generate the server files using the delegate pattern| |false| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| @@ -85,6 +87,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |resourceFolder|resource folder for generated resources| |src/main/resources| |responseWrapper|wrap the responses in given type (Future, Callable, CompletableFuture,ListenableFuture, DeferredResult, RxObservable, RxSingle or fully qualified type)| |null| |returnSuccessCode|Generated server returns 2xx code| |false| +|schemaImplements|Ability to supply interfaces per schema that should be implemented (serves similar purpose as vendor extension `x-implements`, but is fully decoupled from the api spec). Example: yaml `schemaImplements: {Pet: com.some.pack.WithId, Category: [com.some.pack.CategoryInterface], Dog: [com.some.pack.Canine, com.some.pack.OtherInterface]}` implements interfaces in schemas `Pet` (interface `com.some.pack.WithId`), `Category` (interface `com.some.pack.CategoryInterface`), `Dog`(interfaces `com.some.pack.Canine`, `com.some.pack.OtherInterface`)| |empty map| |scmConnection|SCM connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git| |scmDeveloperConnection|SCM developer connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git| |scmUrl|SCM URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| @@ -109,13 +112,14 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useOptional|Use Optional container for optional parameters| |false| |useResponseEntity|Use the `ResponseEntity` type to wrap return values of generated API methods. If disabled, method are annotated using a `@ResponseStatus` annotation, which has the status of the first response declared in the Api definition| |true| |useSealed|Whether to generate sealed model interfaces and classes| |false| -|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| +|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot ≥ 3 (use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| |useSpringBuiltInValidation|Disable `@Validated` at the class level when using built-in validation.| |false| |useSpringController|Annotate the generated API as a Spring Controller| |false| |useSwaggerUI|Open the OpenApi specification in swagger-ui. Will also import and configure needed dependencies| |true| |useTags|use tags for creating interface and controller classnames| |false| |virtualService|Generates the virtual service. For more details refer - https://github.com/virtualansoftware/virtualan/wiki| |false| |withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false| +|xImplementsSkip|Ability to choose interfaces that should NOT be implemented in the models despite their presence in vendor extension `x-implements`. Takes a list of fully qualified interface names. Example: yaml `xImplementsSkip: [com.some.pack.WithPhotoUrls]` skips implementing the interface `com.some.pack.WithPhotoUrls` in any schema| |empty list| ## SUPPORTED VENDOR EXTENSIONS diff --git a/docs/generators/java-dubbo.md b/docs/generators/java-dubbo.md index fa64f3d35955..2ea83de8db02 100644 --- a/docs/generators/java-dubbo.md +++ b/docs/generators/java-dubbo.md @@ -34,10 +34,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configPackage|configuration package for generated code| |org.openapitools.configuration| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-helidon-client.md b/docs/generators/java-helidon-client.md index 5f309c81ce6b..06f803388070 100644 --- a/docs/generators/java-helidon-client.md +++ b/docs/generators/java-helidon-client.md @@ -33,6 +33,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configKey|Config key in @RegisterRestClient. Default to none.| |null| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| diff --git a/docs/generators/java-helidon-server.md b/docs/generators/java-helidon-server.md index b4d8db132743..f456ed9ce064 100644 --- a/docs/generators/java-helidon-server.md +++ b/docs/generators/java-helidon-server.md @@ -32,6 +32,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| diff --git a/docs/generators/java-inflector.md b/docs/generators/java-inflector.md index 3adfffad38df..7054f33501ac 100644 --- a/docs/generators/java-inflector.md +++ b/docs/generators/java-inflector.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-micronaut-client.md b/docs/generators/java-micronaut-client.md index 37a2d8907ee1..645025f315d8 100644 --- a/docs/generators/java-micronaut-client.md +++ b/docs/generators/java-micronaut-client.md @@ -41,10 +41,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |dateFormat|Specify the format pattern of date as a string| |null| |dateLibrary|Option. Date library to use|
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| |datetimeFormat|Specify the format pattern of date-time as a string| |null| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-micronaut-server.md b/docs/generators/java-micronaut-server.md index 4a21268afbd5..73fb9dd977ad 100644 --- a/docs/generators/java-micronaut-server.md +++ b/docs/generators/java-micronaut-server.md @@ -36,10 +36,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |dateFormat|Specify the format pattern of date as a string| |null| |dateLibrary|Option. Date library to use|
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| |datetimeFormat|Specify the format pattern of date-time as a string| |null| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-microprofile.md b/docs/generators/java-microprofile.md index 9e02b37145ef..7f87f275d343 100644 --- a/docs/generators/java-microprofile.md +++ b/docs/generators/java-microprofile.md @@ -37,10 +37,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configKeyFromClassName|If true, set tag as key in @RegisterRestClient. Default to false. Only `microprofile` supports this option.| |null| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-msf4j.md b/docs/generators/java-msf4j.md index 7251308c1440..25842d8df871 100644 --- a/docs/generators/java-msf4j.md +++ b/docs/generators/java-msf4j.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-pkmst.md b/docs/generators/java-pkmst.md index e2299587c5f2..fc5e849f837b 100644 --- a/docs/generators/java-pkmst.md +++ b/docs/generators/java-pkmst.md @@ -33,10 +33,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-play-framework.md b/docs/generators/java-play-framework.md index c5f80ab75d16..f30134f8ec8c 100644 --- a/docs/generators/java-play-framework.md +++ b/docs/generators/java-play-framework.md @@ -35,10 +35,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |controllerOnly|Whether to generate only API interface stubs without the server files.| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-undertow-server.md b/docs/generators/java-undertow-server.md index c258e9aa5df4..1356bc33f589 100644 --- a/docs/generators/java-undertow-server.md +++ b/docs/generators/java-undertow-server.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-vertx-web.md b/docs/generators/java-vertx-web.md index 473c40d1af7d..e4156c53a887 100644 --- a/docs/generators/java-vertx-web.md +++ b/docs/generators/java-vertx-web.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-vertx.md b/docs/generators/java-vertx.md index dd2722079b63..5a8d19f0ee4f 100644 --- a/docs/generators/java-vertx.md +++ b/docs/generators/java-vertx.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java-wiremock.md b/docs/generators/java-wiremock.md index 39b0a40d6edf..e6f238f31ffc 100644 --- a/docs/generators/java-wiremock.md +++ b/docs/generators/java-wiremock.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/java.md b/docs/generators/java.md index b98c5386e4e5..85da80e56a9e 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -37,10 +37,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configKeyFromClassName|If true, set tag as key in @RegisterRestClient. Default to false. Only `microprofile` supports this option.| |null| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-cxf-cdi.md b/docs/generators/jaxrs-cxf-cdi.md index 02f6b177827e..eb7f94c2993d 100644 --- a/docs/generators/jaxrs-cxf-cdi.md +++ b/docs/generators/jaxrs-cxf-cdi.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-cxf-client.md b/docs/generators/jaxrs-cxf-client.md index e735d8f0ef4b..bed567bf4f05 100644 --- a/docs/generators/jaxrs-cxf-client.md +++ b/docs/generators/jaxrs-cxf-client.md @@ -33,10 +33,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-cxf-extended.md b/docs/generators/jaxrs-cxf-extended.md index aeb82d2dce55..00971949946b 100644 --- a/docs/generators/jaxrs-cxf-extended.md +++ b/docs/generators/jaxrs-cxf-extended.md @@ -34,10 +34,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-cxf.md b/docs/generators/jaxrs-cxf.md index b9b120e2f8d9..7325c0b5965b 100644 --- a/docs/generators/jaxrs-cxf.md +++ b/docs/generators/jaxrs-cxf.md @@ -34,10 +34,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-jersey.md b/docs/generators/jaxrs-jersey.md index a5d3e9a3c51a..59186e03fa91 100644 --- a/docs/generators/jaxrs-jersey.md +++ b/docs/generators/jaxrs-jersey.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-resteasy-eap.md b/docs/generators/jaxrs-resteasy-eap.md index 85a3ea082300..ce5dd75fe065 100644 --- a/docs/generators/jaxrs-resteasy-eap.md +++ b/docs/generators/jaxrs-resteasy-eap.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-resteasy.md b/docs/generators/jaxrs-resteasy.md index c03831051659..f451f945b804 100644 --- a/docs/generators/jaxrs-resteasy.md +++ b/docs/generators/jaxrs-resteasy.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/jaxrs-spec.md b/docs/generators/jaxrs-spec.md index 03c2d043bf78..a36ac50aef17 100644 --- a/docs/generators/jaxrs-spec.md +++ b/docs/generators/jaxrs-spec.md @@ -32,10 +32,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |camelCaseDollarSign|Fix camelCase when starting with $ sign. when true : $Value when false : $value| |false| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |legacy| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md index 733e819e6ce3..86859ea27401 100644 --- a/docs/generators/kotlin-server.md +++ b/docs/generators/kotlin-server.md @@ -30,6 +30,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |featureHSTS|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |true| |featureMetrics|Enables metrics feature.| |true| |featureResources|Generates routes in a typed way, for both: constructing URLs and reading the parameters.| |true| +|fixJacksonJsonTypeInfoInheritance|When true (default), ensures Jackson polymorphism works correctly by: (1) always setting visible=true on @JsonTypeInfo, and (2) adding the discriminator property to child models with appropriate default values. When false, visible is only set to true if all children already define the discriminator property.| |true| |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| |interfaceOnly|Whether to generate only API interface stubs without the server files. This option is currently supported only when using jaxrs-spec library.| |false| |library|library template (sub-template)|
    **ktor**
    ktor framework
    **ktor2**
    ktor (2.x) framework
    **jaxrs-spec**
    JAX-RS spec only
    **javalin5**
    Javalin 5
    **javalin6**
    Javalin 6
    |ktor| @@ -262,11 +263,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl | ---- | --------- | ---------- | |Simple|✓|OAS2,OAS3 |Composite|✓|OAS2,OAS3 -|Polymorphism|✗|OAS2,OAS3 +|Polymorphism|✓|OAS2,OAS3 |Union|✗|OAS3 -|allOf|✗|OAS2,OAS3 +|allOf|✓|OAS2,OAS3 |anyOf|✗|OAS3 -|oneOf|✗|OAS3 +|oneOf|✓|OAS3 |not|✗|OAS3 ### Security Feature diff --git a/docs/generators/kotlin-spring.md b/docs/generators/kotlin-spring.md index 9dfba5d3e6c8..0c4e836ad7fa 100644 --- a/docs/generators/kotlin-spring.md +++ b/docs/generators/kotlin-spring.md @@ -43,6 +43,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl |parcelizeModels|toggle "@Parcelize" for generated models| |null| |reactive|use coroutines for reactive behavior| |false| |requestMappingMode|Where to generate the class level @RequestMapping annotation.|
    **api_interface**
    Generate the @RequestMapping annotation on the generated Api Interface.
    **controller**
    Generate the @RequestMapping annotation on the generated Api Controller Implementation.
    **none**
    Do not add a class level @RequestMapping annotation.
    |controller| +|schemaImplements|A map of single interface or a list of interfaces per schema name that should be implemented (serves similar purpose as `x-kotlin-implements`, but is fully decoupled from the api spec). Example: yaml `schemaImplements: {Pet: com.some.pack.WithId, Category: [com.some.pack.CategoryInterface], Dog: [com.some.pack.Canine, com.some.pack.OtherInterface]}` implements interfaces in schemas `Pet` (interface `com.some.pack.WithId`), `Category` (interface `com.some.pack.CategoryInterface`), `Dog`(interfaces `com.some.pack.Canine`, `com.some.pack.OtherInterface`)| |empty map| +|schemaImplementsFields|A map of single field or a list of fields per schema name that should be prepended with `override` (serves similar purpose as `x-kotlin-implements-fields`, but is fully decoupled from the api spec). Example: yaml `schemaImplementsFields: {Pet: id, Category: [name, id], Dog: [bark, breed]}` marks fields to be prepended with `override` in schemas `Pet` (field `id`), `Category` (fields `name`, `id`) and `Dog` (fields `bark`, `breed`)| |empty map| |serializableModel|boolean - toggle "implements Serializable" for generated models| |null| |serverPort|configuration the port in which the sever is to run on| |8080| |serviceImplementation|generate stub service implementations that extends service interfaces. If this is set to true service interfaces will also be generated| |false| @@ -56,9 +58,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useFeignClientUrl|Whether to generate Feign client with url parameter.| |true| |useFlowForArrayReturnType|Whether to use Flow for array/collection return types when reactive is enabled. If false, will use List instead.| |true| |useResponseEntity|Whether (when false) to return actual type (e.g. List<Fruit>) and handle non-happy path responses via exceptions flow or (when true) return entire ResponseEntity (e.g. ResponseEntity<List<Fruit>>). If disabled, method are annotated using a @ResponseStatus annotation, which has the status of the first response declared in the Api definition| |true| -|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| +|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot ≥ 3 (use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| |useSwaggerUI|Open the OpenApi specification in swagger-ui. Will also import and configure needed dependencies| |true| |useTags|Whether to use tags for creating interface and controller class names| |false| +|xKotlinImplementsFieldsSkip|A list of fields per schema name that should NOT be created with `override` keyword despite their presence in vendor extension `x-kotlin-implements-fields` for the schema. Example: yaml `xKotlinImplementsFieldsSkip: Pet: [photoUrls]` skips `override` for `photoUrls` in schema `Pet`| |empty map| +|xKotlinImplementsSkip|A list of fully qualified interfaces that should NOT be implemented despite their presence in vendor extension `x-kotlin-implements`. Example: yaml `xKotlinImplementsSkip: [com.some.pack.WithPhotoUrls]` skips implementing the interface in any schema| |empty list| ## SUPPORTED VENDOR EXTENSIONS diff --git a/docs/generators/protobuf-schema.md b/docs/generators/protobuf-schema.md index fc8616619336..e01683760038 100644 --- a/docs/generators/protobuf-schema.md +++ b/docs/generators/protobuf-schema.md @@ -22,6 +22,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |aggregateModelsName|Aggregated model filename. If set, all generated models will be combined into this single file.| |null| |customOptionsApi|Custom options for the api files.| |null| |customOptionsModel|Custom options for the model files.| |null| +|extractEnumsToSeparateFiles|Extract enums to separate protobuf files and import them in models| |false| |numberedFieldNumberList|Field numbers in order.| |false| |startEnumsWithUnspecified|Introduces "UNSPECIFIED" as the first element of enumerations.| |false| |supportMultipleResponses|Support multiple responses| |true| diff --git a/docs/generators/python-fastapi.md b/docs/generators/python-fastapi.md index 5a87a2fcee28..4e706a4c1a52 100644 --- a/docs/generators/python-fastapi.md +++ b/docs/generators/python-fastapi.md @@ -10,7 +10,7 @@ title: Documentation for the python-fastapi Generator | generator stability | BETA | | | generator type | SERVER | | | generator language | Python | | -| generator language version | 3.7 | | +| generator language version | 3.10 | | | generator default templating engine | mustache | | | helpTxt | Generates a Python FastAPI server (beta). Models are defined with the pydantic library | | diff --git a/docs/generators/spring.md b/docs/generators/spring.md index 2af0fe826a3e..854118300bda 100644 --- a/docs/generators/spring.md +++ b/docs/generators/spring.md @@ -37,11 +37,13 @@ These options may be applied as additional-properties (cli) or configOptions (pl |configPackage|configuration package for generated code| |org.openapitools.configuration| |containerDefaultToNull|Set containers (array, set, map) default to null| |false| |dateLibrary|Option. Date library to use|
    **joda**
    Joda (for legacy app only)
    **legacy**
    Legacy java.util.Date
    **java8-localdatetime**
    Java 8 using LocalDateTime (for legacy app only)
    **java8**
    Java 8 native JSR310 (preferred for jdk 1.8+)
    |java8| +|defaultToEmptyContainer|Initialize containers (array/set/map) to empty containers instead of null by default. Usage: https://github.com/OpenAPITools/openapi-generator/blob/master/docs/customization.md#default-values| |null| |delegatePattern|Whether to generate the server files using the delegate pattern| |false| |developerEmail|developer email in generated pom.xml| |team@openapitools.org| |developerName|developer name in generated pom.xml| |OpenAPI-Generator Contributors| |developerOrganization|developer organization in generated pom.xml| |OpenAPITools.org| |developerOrganizationUrl|developer organization URL in generated pom.xml| |http://openapitools.org| +|disableDiscriminatorJsonIgnoreProperties|Ignore discriminator field type for Jackson serialization| |false| |disableHtmlEscaping|Disable HTML escaping of JSON strings when using gson (needed to avoid problems with byte[] fields)| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |discriminatorCaseSensitive|Whether the discriminator value lookup should be case-sensitive or not. This option only works for Java API client| |true| @@ -78,6 +80,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |resourceFolder|resource folder for generated resources| |src/main/resources| |responseWrapper|wrap the responses in given type (Future, Callable, CompletableFuture,ListenableFuture, DeferredResult, RxObservable, RxSingle or fully qualified type)| |null| |returnSuccessCode|Generated server returns 2xx code| |false| +|schemaImplements|Ability to supply interfaces per schema that should be implemented (serves similar purpose as vendor extension `x-implements`, but is fully decoupled from the api spec). Example: yaml `schemaImplements: {Pet: com.some.pack.WithId, Category: [com.some.pack.CategoryInterface], Dog: [com.some.pack.Canine, com.some.pack.OtherInterface]}` implements interfaces in schemas `Pet` (interface `com.some.pack.WithId`), `Category` (interface `com.some.pack.CategoryInterface`), `Dog`(interfaces `com.some.pack.Canine`, `com.some.pack.OtherInterface`)| |empty map| |scmConnection|SCM connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git| |scmDeveloperConnection|SCM developer connection in generated pom.xml| |scm:git:git@github.com:openapitools/openapi-generator.git| |scmUrl|SCM URL in generated pom.xml| |https://github.com/openapitools/openapi-generator| @@ -102,13 +105,14 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useOptional|Use Optional container for optional parameters| |false| |useResponseEntity|Use the `ResponseEntity` type to wrap return values of generated API methods. If disabled, method are annotated using a `@ResponseStatus` annotation, which has the status of the first response declared in the Api definition| |true| |useSealed|Whether to generate sealed model interfaces and classes| |false| -|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| +|useSpringBoot3|Generate code and provide dependencies for use with Spring Boot ≥ 3 (use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.| |false| |useSpringBuiltInValidation|Disable `@Validated` at the class level when using built-in validation.| |false| |useSpringController|Annotate the generated API as a Spring Controller| |false| |useSwaggerUI|Open the OpenApi specification in swagger-ui. Will also import and configure needed dependencies| |true| |useTags|use tags for creating interface and controller classnames| |false| |virtualService|Generates the virtual service. For more details refer - https://github.com/virtualansoftware/virtualan/wiki| |false| |withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false| +|xImplementsSkip|Ability to choose interfaces that should NOT be implemented in the models despite their presence in vendor extension `x-implements`. Takes a list of fully qualified interface names. Example: yaml `xImplementsSkip: [com.some.pack.WithPhotoUrls]` skips implementing the interface `com.some.pack.WithPhotoUrls` in any schema| |empty list| ## SUPPORTED VENDOR EXTENSIONS diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index 9d565bf5993f..68376d466186 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -7,7 +7,7 @@ title: Documentation for the swift5 Generator | Property | Value | Notes | | -------- | ----- | ----- | | generator name | swift5 | pass this to the generate command after -g | -| generator stability | STABLE | | +| generator stability | DEPRECATED | | | generator type | CLIENT | | | generator language | Swift | | | generator default templating engine | mustache | | diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index 7d7c88af9979..f9f96573a4af 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -11,7 +11,7 @@ title: Documentation for the typescript-angular Generator | generator type | CLIENT | | | generator language | Typescript | | | generator default templating engine | mustache | | -| helpTxt | Generates a TypeScript Angular (9.x - 20.x) client library. | | +| helpTxt | Generates a TypeScript Angular (9.x - 21.x) client library. | | ## CONFIG OPTIONS These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. @@ -34,7 +34,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |modelSuffix|The suffix of the generated model.| |null| |ngPackagrVersion|The version of ng-packagr compatible with Angular (see ngVersion option).| |null| -|ngVersion|The version of Angular. (At least 9.0.0)| |20.0.0| +|ngVersion|The version of Angular. (At least 9.0.0)| |21.0.0| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/docs/generators/typescript-axios.md b/docs/generators/typescript-axios.md index 269c2b09587e..62f77eca1828 100644 --- a/docs/generators/typescript-axios.md +++ b/docs/generators/typescript-axios.md @@ -20,7 +20,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | ------ | ----------- | ------ | ------- | |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |apiPackage|package for generated api classes| |null| -|axiosVersion|Use this property to override the axios version in package.json| |^1.6.1| +|axiosVersion|Use this property to override the axios version in package.json| |^1.13.5| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names.| |Enum| diff --git a/docs/generators/typescript.md b/docs/generators/typescript.md index 5634f424a966..8616f926108d 100644 --- a/docs/generators/typescript.md +++ b/docs/generators/typescript.md @@ -42,6 +42,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |supportsES6|Generate code that conforms to ES6.| |false| +|typescriptMajorVersion|Specify the major version of TypeScript to use in the client code. Default is 5.| |5| |useErasableSyntax|Use erasable syntax for the generated code. This is a temporary feature and will be removed in the future.| |false| |useInversify|Enable this to generate decorators and service identifiers for the InversifyJS inversion of control container. If you set 'deno' as 'platform', the generator will process this value as 'disable'.| |false| |useObjectParameters|Use aggregate parameter objects as function arguments for api operations instead of passing each parameter as a separate function argument.| |false|