Skip to content
This repository was archived by the owner on Dec 25, 2024. It is now read-only.

Latest commit

 

History

History
437 lines (387 loc) · 27.2 KB

File metadata and controls

437 lines (387 loc) · 27.2 KB

This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: " \

This Java package is automatically generated by the OpenAPI JSON Schema Generator project:

  • API version: 1.0.0
  • Package version:
  • Build package: JavaClientGenerator

Requirements

Java 17

Migration Guides

Installation

pip install

If the python package is hosted on a repository, you can install directly using:

pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git

(you may need to run pip with root permission: sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git)

Then import the package:

import org.openapijsonschematools

Setuptools

Install via Setuptools.

python -m pip install . --user

(or python -m pip install . to install the package for all users)

Then import the package:

import org.openapijsonschematools

Usage Notes

Validation, Immutability, and Data Type

This python code validates data to schema classes and return back an immutable instance containing the data which subclasses all validated schema classes. This ensure that

  • valid data cannot be mutated and become invalid to a set of schemas
    • the one exception is that files are not immutable, so schema instances storing/sending/receiving files are not immutable

Here is the mapping from json schema types to python subclassed types:

Json Schema Type Python Base Class
object schemas.immutabledict
array tuple
string str
number float, int
integer int
boolean bool
null None
AnyType (unset) typing.Union[schemas.immutabledict, tuple, str, float, int, bool, None]

Storage of Json Schema Definition in Python Classes

In openapi v3.0.3 there are ~ 28 json schema keywords. Almost all of them can apply if type is unset. I have chosen to separate the storage of json schema definition info and output validated classes for payload instantiation.

Reason

This json schema data is stored in each class that is written for a schema, in a component or other openapi document location. This class is only responsible for storing schema info. Output classes like those that store dict payloads are written separately and are returned by the Schema.validate method when that method is passed in dict input. This prevents payload property access methods from colliding with json schema definition.

Json Schema Type Object

Most component schemas (models) are probably of type object. Which is a map data structure. Json schema allows string keys in this map, which means schema properties can have key names that are invalid python variable names. Names like:

  • "hi-there"
  • "1variable"
  • "@now"
  • " "
  • "from"

To allow these use cases to work, schemas.immutabledict is used as the base class of type object schemas. This means that one can use normal dict methods on instances of these classes.

Other Details
  • optional properties which were not set will not exist in the instance
  • None is only allowed in as a value if type: "null" was included or nullable: true was set
  • preserving the original key names is required to properly validate a payload to multiple json schemas

Json Schema Type + Format, Validated Data Storage

N schemas can be validated on the same payload. To allow multiple schemas to validate, the data must be stored using one base class whether or not a json schema format constraint exists in the schema. See the below accessors for string data:

  • type string + format: See schemas.as_date, schemas.as_datetime, schemas.as_decimal, schemas.as_uuid

In json schema, type: number with no format validates both integers and floats, so int and float values are stored for type number.

String + Date Example

For example the string payload '2023-12-20' is validates to both of these schemas:

  1. string only
- type: string
  1. string and date format
- type: string
  format: date

Because of use cases like this, a datetime.date is allowed as an input to this schema, but the data is stored as a string.

Getting Started

Please follow the installation procedure and then run the following:

// TODO paths/path/verb/_helper_operation_doc_example

Servers

server_index Class Description
0 Model0 petstore server
1 Model1 The local server
2 Model2 staging server with no variables

Endpoints

All URIs are relative to the selected server

  • The server is selected by passing in server_info and server_index into api_configuration.ApiConfiguration
  • Code samples in endpoints documents show how to do this
  • server_index can also be passed in to endpoint calls, see endpoint documentation
HTTP request Method Description
/ get FakeApi.slash_route slash route
/another-fake/dummy patch $anotherFake?Api.123_test_@#__%_special_tags To test special tags
/commonParam/{subDir}/ delete FakeApi.delete_common_param
/commonParam/{subDir}/ get FakeApi.get_common_param
/commonParam/{subDir}/ post FakeApi.post_common_param
/fake delete FakeApi.group_parameters Fake endpoint to test group parameters (optional)
/fake get FakeApi.enum_parameters To test enum parameters
/fake patch FakeApi.client_model To test "client" model
/fake post FakeApi.endpoint_parameters Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
/fake/additional-properties-with-array-of-enums get FakeApi.additional_properties_with_array_of_enums Additional Properties with Array of Enums
/fake/body-with-file-schema put FakeApi.body_with_file_schema
/fake/body-with-query-params put FakeApi.body_with_query_params
/fake/case-sensitive-params put FakeApi.case_sensitive_params
/fake/deleteCoffee/{id} delete FakeApi.delete_coffee Delete coffee
/fake/health get FakeApi.fake_health_get Health check endpoint
/fake/inline-additionalProperties post FakeApi.inline_additional_properties test inline additionalProperties
/fake/inlineComposition/ post FakeApi.inline_composition testing composed schemas at inline locations
/fake/jsonFormData get FakeApi.json_form_data test json serialization of form data
/fake/jsonPatch patch FakeApi.json_patch json patch
/fake/jsonWithCharset post FakeApi.json_with_charset json with charset tx and rx
/fake/multipleRequestBodyContentTypes/ post FakeApi.multiple_request_body_content_types testing composed schemas at inline locations
/fake/multipleResponseBodies get FakeApi.multiple_response_bodies multiple responses have response bodies
/fake/multipleSecurities get FakeApi.multiple_securities multiple security requirements
/fake/objInQuery get FakeApi.object_in_query user list
/fake/parameterCollisions/{1}/{aB}/{Ab}/{self}/{A-B}/ post FakeApi.parameter_collisions parameter collision case
/fake/queryParamWithJsonContentType get FakeApi.query_param_with_json_content_type query param with json content-type
/fake/redirection get FakeApi.redirection operation with redirection responses
/fake/refObjInQuery get FakeApi.ref_object_in_query user list
/fake/refs/array-of-enums post FakeApi.array_of_enums Array of Enums
/fake/refs/arraymodel post FakeApi.array_model
/fake/refs/boolean post FakeApi.boolean
/fake/refs/composed_one_of_number_with_validations post FakeApi.composed_one_of_different_types
/fake/refs/enum post FakeApi.string_enum
/fake/refs/mammal post FakeApi.mammal
/fake/refs/number post FakeApi.number_with_validations
/fake/refs/object_model_with_ref_props post FakeApi.object_model_with_ref_props
/fake/refs/string post FakeApi.string
/fake/responseWithoutSchema get FakeApi.response_without_schema receives a response without schema
/fake/test-query-paramters put FakeApi.query_parameter_collection_format
/fake/uploadDownloadFile post FakeApi.upload_download_file uploads a file and downloads a file using application/octet-stream
/fake/uploadFile post FakeApi.upload_file uploads a file using multipart/form-data
/fake/uploadFiles post FakeApi.upload_files uploads files using multipart/form-data
/fake/wildCardResponses get FakeApi.wild_card_responses operation with wildcard responses
/fake/{petId}/uploadImageWithRequiredFile post PetApi.upload_file_with_required_file uploads an image (required)
/fake_classname_test patch [FakeClassnameTags 123#$%^Api](docs/FakeClassnameTags 123#$%^Api.md).classname To test class name in snake case
/foo get DefaultApi.foo_get
/pet post PetApi.add_pet Add a new pet to the store
/pet put PetApi.update_pet Update an existing pet
/pet/findByStatus get PetApi.find_pets_by_status Finds Pets by status
/pet/findByTags get PetApi.find_pets_by_tags Finds Pets by tags
/pet/{petId} delete PetApi.delete_pet Deletes a pet
/pet/{petId} get PetApi.get_pet_by_id Find pet by ID
/pet/{petId} post PetApi.update_pet_with_form Updates a pet in the store with form data
/pet/{petId}/uploadImage post PetApi.upload_image uploads an image
/store/inventory get StoreApi.get_inventory Returns pet inventories by status
/store/order post StoreApi.place_order Place an order for a pet
/store/order/{order_id} delete StoreApi.delete_order Delete purchase order by ID
/store/order/{order_id} get StoreApi.get_order_by_id Find purchase order by ID
/user post UserApi.create_user Create user
/user/createWithArray post UserApi.create_users_with_array_input Creates list of users with given input array
/user/createWithList post UserApi.create_users_with_list_input Creates list of users with given input array
/user/login get UserApi.login_user Logs user into the system
/user/logout get UserApi.logout_user Logs out current logged in user session
/user/{username} delete UserApi.delete_user Delete user
/user/{username} get UserApi.get_user_by_name Get user by user name
/user/{username} put UserApi.update_user Updated user

Component Schemas

Class Description
Schema200Response1 model with an invalid class name for python, starts with a number
AbstractStepMessage1 Abstract Step
AdditionalPropertiesClass1
AdditionalPropertiesSchema1
AdditionalPropertiesWithArrayOfEnums1
Address1
Animal1
AnimalFarm1
AnyTypeAndFormat1
AnyTypeNotString1
ApiResponseSchema1
ArrayHoldingAnyType1
ArrayOfArrayOfNumberOnly1
ArrayOfEnums1
ArrayOfNumberOnly1
ArrayTest1
ArrayWithValidationsInItems1
Bar1
BasquePig1
BooleanSchema1
BooleanEnum1
Capitalization1
Cat1
Category1
ChildCat1
ClassModel1 Model for testing model with "_class" property
Client1
ComplexQuadrilateral1
ComposedAnyOfDifferentTypesNoValidations1
ComposedArray1
ComposedBool1
ComposedNone1
ComposedNumber1
ComposedObject1
ComposedOneOfDifferentTypes1 this is a model that allows payloads of type object or number
ComposedString1
Currency1
DanishPig1
DateTimeTest1
DateTimeWithValidations1
DateWithValidations1
DecimalPayload1
Dog1
Drawing1
EnumArrays1
EnumClass1
EnumTest1
EquilateralTriangle1
File1 Must be named `File` for test.
FileSchemaTestClass1
Foo1
FormatTest1
FromSchema1
GrandparentAnimal1
HealthCheckResult1 Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model.
IntegerEnum1
IntegerEnumBig1
IntegerEnumOneValue1
IntegerEnumWithDefaultValue1
IntegerMax101
IntegerMin151
IsoscelesTriangle1
Items1 component's name collides with the inner schema name
JSONPatchRequest1
JSONPatchRequestAddReplaceTest1
JSONPatchRequestMoveCopy1
JSONPatchRequestRemove1
MapTest1
MixedPropertiesAndAdditionalPropertiesClass1
Money1
MyObjectDto1
Name1 Model for testing model name same as property name
NoAdditionalProperties1
NullableClass1
NullableShape1 The value may be a shape or the 'null' value. For a composed schema to validate a null payload, one of its chosen oneOf schemas must be type null or nullable (introduced in OAS schema >= 3.0)
NullableString1
NumberSchema1
NumberOnly1
NumberWithValidations1
ObjWithRequiredProps1
ObjWithRequiredPropsBase1
ObjectInterface1
ObjectModelWithArgAndArgsProperties1
ObjectModelWithRefProps1 a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations
ObjectWithAllOfWithReqTestPropFromUnsetAddProp1
ObjectWithCollidingProperties1 component with properties that have name collisions
ObjectWithDecimalProperties1
ObjectWithDifficultlyNamedProps1 model with properties that have invalid names for python
ObjectWithInlineCompositionProperty1
ObjectWithInvalidNamedRefedProperties1
ObjectWithNonIntersectingValues1
ObjectWithOnlyOptionalProps1
ObjectWithOptionalTestProp1
ObjectWithValidations1
Order1
PaginatedResultMyObjectDto1
ParentPet1
Pet1 Pet object that needs to be added to the store
Pig1
Player1 a model that includes a self reference this forces properties and additionalProperties to be lazy loaded in python models because the Player class has not fully loaded when defining properties
PublicKey1 schema that contains a property named key
Quadrilateral1
QuadrilateralInterface1
ReadOnlyFirst1
RefPet1
ReqPropsFromExplicitAddProps1
ReqPropsFromTrueAddProps1
ReqPropsFromUnsetAddProps1
ReturnSchema1 Model for testing reserved words
ScaleneTriangle1
SelfReferencingArrayModel1
SelfReferencingObjectModel1
Shape1
ShapeOrNull1 The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1.
SimpleQuadrilateral1
SomeObject1
StringSchema1
StringBooleanMap1
StringEnum1
StringEnumWithDefaultValue1
StringWithValidation1
Tag1
Triangle1
TriangleInterface1
UUIDString1
User1
SpecialModelname1 model with an invalid class name for python
Apple1
AppleReq1
Banana1
BananaReq1
Fruit1
FruitReq1
GmFruit1
HasOnlyReadOnly1
Mammal1
Whale1
Zebra1

Component RequestBodies

Class Description
Client client model
Pet Pet object that needs to be added to the store, multiple content types
RefUserArray
UserArray List of user object

Component Responses

Class Description
HeadersWithNoBody A response that contains headers but no body
RefSuccessDescriptionOnly
RefSuccessfulXmlAndJsonArrayOfPet
SuccessDescriptionOnly Success
SuccessInlineContentAndHeader successful operation
SuccessWithJsonApiResponse successful operation
SuccessfulXmlAndJsonArrayOfPet successful operation, multiple content types

Component Headers

Class Description
Int32JsonContentTypeHeader int32 JSON content-type header
NumberHeader number header description
RefContentSchemaHeader int32 JSON content-type header
RefSchemaHeader header that has a ref in the schema
RefStringHeader
StringHeader string header description

Component Parameters

Class Description
ComponentRefSchemaStringWithValidation a path string with validation
PathUserName the use name to use
RefPathUserName
RefSchemaStringWithValidation a path string with validation

Component SecuritySchemes

Class Description
ApiKey apiKey in header
ApiKeyQuery apiKey in query
BearerTest http bearer with JWT bearer format
HttpBasicTest http basic
HttpSignatureTest http + signature
OpenIdConnectTest openIdConnect
PetstoreAuth oauth2 implicit flow with two scopes

Notes for Large OpenAPI documents

If the OpenAPI document is large, imports in org.openapijsonschematools.apis.tags.tag_to_api and org.openapijsonschematools.components.schemass may fail with a RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions:

Solution 1: Use specific imports for apis and models like:

  • tagged api: from org.openapijsonschematools.apis.tags.default_api import DefaultApi
  • api for one path: from org.openapijsonschematools.apis.paths.some_path import SomePath
  • api for one operation (path + verb): from org.openapijsonschematools.paths.some_path.get import ApiForget
  • single model import: from org.openapijsonschematools.components.schemas.pet import Pet

Solution 2: Before importing the package, adjust the maximum recursion limit as shown below:

import sys
sys.setrecursionlimit(1500)
import org.openapijsonschematools
from org.openapijsonschematools.apis.tags.tag_to_api import *
from org.openapijsonschematools.components.schemass import *