I would like to correctly render a hashmap (key: a UUID, value: an object) both in the Response schema AND the Response samples (examples) sections of my API doc such:
{
"objects": {
"3a34655e-9566-4d5e-bce7-8fa71670993b": {
"title": "Foo"
},
"4bb806a9-fcd1-4a32-b2f0-6cbb45cfc894": {
"title": "Bar"
}
}
}
I'm working on a Symfony 6 project with these libraries which should be compatible with OpenAPI 3.0 and 3.1 specifications:
zircote/swagger-php(version:4.7.10)nelmio/api-doc-bundle(version:v4.11.1)
Reading this related StackOverflow answer, I considered 2 options:
OPTION 1 - AdditionalProperties
/**
* @var array<string, ObjectDto>
*
* @OA\Property(
* type="object",
* @OA\AdditionalProperties(
* type="object",
* ref=@Model(type=ObjectDto::class),
* ),
* description="The objects indexed by ID"
* )
*/
Problem
I didn't find any way to override the property name* assigned by default to the hashmap's key rendered in the Response schema section, nor the "property1" and "property2" rendered in the Response samples section:
"objects": {
"property1": { ... },
"property2": { ... }
},
I would be able to customize the key's information
OPTION 2 - patternProperties
/**
* @var array<string, ObjectDto>
*
* @OA\Property(
* type="object",
* patternProperties={
* "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"=@OA\Property(
* type="object",
* ref=@Model(type=ObjectDto::class),
* )
* },
* description="The objects indexed by ID"
* )
*/
Problem
The Response schema section is OK, but the example generated in the Response samples section is empty, I get:
"objects": { }
QUESTION
Did I miss something? Is it possible to have a full control on the rendering of a hashmap using OpenAPI Specification 3.1?
OpenAPI 3.0 doesn't seem to support using, or even the imitating the effect of patternProperties. You'll see it mentioned in some of their proposals, but as of Sep, 2023, it isn't implemented. You'll need to convert mapped objects into arrays that describe the key value pair, either as an object-array, or tuples. Or you could be in my shoes, having no access to change the presentation of the data from the backend, and silently weep at the loss of type safety.
Took me forever to figure this out, and the answer is on this page. OpenAPI uses a modified version of jsonSchema to describe objects, that supports additional keys, and drops support for others, including our belov'd patternProperties.
They offer the following page which provides information on handling dictionaries, hash maps, etc - though nothing I can find regarding specific key handling patterns.