The oneOf Keyword
In support of the OpenAPI Specification oneOf
schemas, Speakeasy SDKs provide language-specific implementations based on idiomatic unions (when available) or using generated supporting objects that allow type safety by using an enum
discriminator.
Supporting Objects
Assuming your spec has a Pet
component, consider this oneOf
block:
oneOf: - type: string - type: integer - $ref: "/components/schemas/Pet"
How Speakeasy generates supporting objects for your SDK depends on the language of the SDK.
Speakeasy leverages native TypeScript support for unions to represent oneOf
schemas. A union type is generated to represent the different possible types defined in the oneOf
schema.
Requests
Assume you have an operation that allows the user to fetch a pet by submitting the pet's name, ID, or complete pet object:
/pet: get: operationId: fetchPet parameters: - name: pet schema: oneOf: - type: string - type: integer - $ref: "/components/schemas/Pet"
const sdk = new SDK();sdk.pets.fetchPet("Fido"); // stringsdk.pets.fetchPet(123); // numbersdk.pets.fetchPet({ id: "p-123" }); // Pet object
Responses
Sometimes you may have a response that specifies a oneOf
schema. For languages that do not natively support unions, Speakeasy will create supporting objects to deserialize the oneOf
response into the correct object type. No supported objects are needed for languages with native union types, so Speakeasy will deserialize into the native type.
For example, this schema:
/pet_id: get: operationId: petId responses: "200": description: OK content: application/json: schema: title: res oneOf: - type: string - type: integer
Will result in these response types:
type PetIdRes = string | number;
Splitting oneOf
Schema Types
By defining similar operations with aligned but different schemas, you can apply x-speakeasy-type-override: any
for untyped operations and use oneOf
to define stricter types in others. This allows for methods like DoSomething(StrictObject{...})
alongside DoSomethingUntyped({...})
, providing flexibility across SDK methods based on the required schema type.
This approach is particularly useful when dealing with endpoints that require splitting oneOf
schema types into separate SDK methods.
Example:
/sources#SellerPartner: post: requestBody: content: application/json: schema: $ref: "#/components/schemas/SourceSellerPartnerCreateRequest" tags: - "Sources" responses: "200": content: application/json: schema: $ref: "#/components/schemas/SourceResponse" description: "Successful operation" "400": description: "Invalid data" "403": description: "Not allowed" operationId: "createSourceSellerPartner" summary: "Create a source" description: "Creates a source given a name, workspace ID, and a JSON blob containing the configuration for the source." x-use-speakeasy-middleware: true x-speakeasy-entity-operation: Source_SellerPartner#create