Response types
By default, the client will expect the response types to be equivalent, independently of the resulting media type, as such if multiple response types are available, the client will return the union of all possible response types.
This can become an issue for APIs which use media type versioning returning multiple response types based on the Accept
header sent by the client.
To handle this, the generated client composables and $[client]
helper expose an additional accept
option with enhanced type inference.
accept
option will always override the Accept
header sent by the client, even if overridden in the ofetch
options.Example
Given an OpenAPI spec with the following response types for the /pet/{petId}
endpoint:
responses:
'200':
content:
application/x.petstore.pet+json;version=1:
schema:
$ref: '#/components/schemas/PetV1'
application/x.petstore.pet+json;version=2:
schema:
$ref: '#/components/schemas/PetV2'
By default, the client will return a union of both PetV1
and PetV2
types when calling the endpoint without specifying an accept
header.
const { data } = await usePets('/pet/{petId}', {
path: {
petId: 1
}
})
// typeof data.value = PetV1 | PetV2
By using the accept
option, you can specify which media type you want to receive, allowing the client to return a more specific type.
const { data: v1Data } = await usePets('/pet/{petId}', {
path: {
petId: 1
},
accept: 'application/x.petstore.pet+json;version=1'
})
// typeof v1Data.value = PetV1
const { data: v2Data } = await usePets('/pet/{petId}', {
path: {
petId: 1
},
accept: 'application/x.petstore.pet+json;version=2'
})
// typeof v2Data.value = PetV2
If for some reason you want to accept multiple media types, you can pass an array of media types to the accept
option,
which will result in the client returning the union of all requested media types.
const { data } = await usePets('/pet/{petId}', {
path: {
petId: 1
},
accept: [
'application/x.petstore.pet+json;version=1',
'application/x.petstore.pet+json;version=2'
]
})
// typeof data.value = PetV1 | PetV2