Making ad-hoc API calls type-safe
I’ve had to integrate a few legacy APIs recently; some with SDKs that lack type definition, like the Atriusmaps Node SDK. I’ve fallen into a pattern of using tools like Zod and Valibot to parse the incoming data, for two reasons:
- It gives me a type-safe object to play with - so I get all the typescript benefits like auto-completion, checking etc.
- It flags any data that’s shaped unexpectedly with a nice, clear exception - so I don’t end up having to step through
Cannot read properties of undefined
errors. - It’s easier to reason with a Zod schema than the equivalent, manual type definition.
I’ve also found that GPT does a very good job of generating Zod schemas from Jbuilder views, so adding type safety to a Rails API request is a doddle. Will definitely be leaning into this pattern more and more.