-
Notifications
You must be signed in to change notification settings - Fork 9
Clients
Features that API clients should support.
API operations that have more than a few (one?) parameters should use an object to contain those parameters, rather than having multiple function parameters. Many languages do not have named parameters, which makes code vulnerable to errors if parameters are reordered. It also makes it hard to read, and to manage optionality when there are multiple unnamed parameters.
All responses should enjoy type safety, including default and non-default responses. Responses are identified by HTTP status code and content-type.
Some languages (eg. TypeScript) don’t support type-safe exceptions or errors. Those languages may need to adopt return types that expose the HTTP status code and content-type along with associated types to enable type-safe response handling.
Safety from unknown enum values being received is important as APIs evolve, and a new enum value is sometimes added without versioning the API (because versioning is a pain). Handling unknown enum values as a first-class part of an API protects client applications from unexpected behaviour or crashes when new values are introduced.
An API enum should have an Unknown option, and ideally a way to discover the original unknown value.
Supporting unknown enum values requires a parsed response approach.
Swift’s native enums support associated values, so an unknown enum value can contain the actual value received so it can be inspected in code at runtime.
Languages that don’t have enums with associated values would need an alternative to providing access to the unknown enum value. In order to avoid breaking the convenience of using native enums, the raw enum value could be made available on the original object as a string.
Parsing the response to turn it into model objects can ensure that the response is valid, only contains the expected properties and values, and uses the best native types.
Compare this with the JavaScript / TypeScript possible approach of simply deserialising the JSON into objects, where any properties received will be present at runtime, possibly resulting in unexpected behaviour. Furthermore native types may be used for date and time values (although the built-in native types are poor).
Validating API responses is a useful addition to a client to ensure that the API contract is upheld by the server. API requests can be rejected like a network error occurred, to prevent invalid data reaching the application.
Validation should not include additional properties, as additional properties are often added to an API without versioning if they are known or thought not to cause faults in existing API clients. Additional properties should however be filtered out, as above, so they do not exist in application code at runtime.