IPA-125: Single Type in Request and Response
API requests and responses should strive for clarity by representing each field with a single, well-defined type. This helps maintain consistency and reduces ambiguity for API consumers. This convention also ensures that downstream tooling is well-supported and prevents issues for IaC tools as it simplifies state management.
State
Adopt
Guidance
- Splitting Fields for Multiple Value Types
- API producers should not use oneOf with base types like int or string if the field can have multiple distinct value types
- API producers should split such fields into separate, clearly named fields with appropriate types
- API producers may use fields that contain multiple objects when request
and response objects allow explicitly setting the type of the object
- In OpenAPI each
oneOf
property must be accompanied by adiscriminator
property defining when the exact type will be used - In OpenAPI each
discriminator
property must be accompanied by aoneOf
,anyOf
orallOf
property (OAS 3.1.0 4.8.25.1) - If multiple
oneOf
models define a property with the same name, that property must have the same data type in each model
- In OpenAPI each
Example
Avoid this design, using the same field for multiple types:
POST /groups/search/index
{
"indexArray": false, // Can be a boolean, an array or a single object
}
Preferred design, splitting the field into distinct types:
POST /groups/search/index
{
"isArray": false, //Explicitly a boolean
"indexArrayObjects": [{<object1>}, {<object2>}], //Expilicitly an array
"singleIndexObject": {"key1": "value1", "key2": "value2"} //Explicitly a single object
}