Generating a Zod schema from an API response sample, and what a sample can’t tell you
Disclosure: I built the converter used in this post. The Zod code below is useful without it. TypeScript types disappear at runtime. const user: User = await res.json() checks nothing. Zod validates data where it enters your app, so a first-draft schema from a sample response saves typing. Here is a sample response: { "id" : 4182 , "email" : "ada@example.com" , "createdAt" :…
The article discusses generating Zod schemas from API response samples and the limitations of relying solely on samples. The author built a converter for this purpose, stating that TypeScript types disappear at runtime, making validation essential. A sample response is provided, which is then used to generate a Zod schema.
However, the article highlights what a single sample cannot tell you. There are two order schemas in the sample, each with different keys, leading to a union type when creating the final schema. To merge these, you must handle them manually. The sample also shows that the `avatarUrl` field can be either a string or null, but the nullable type is only inferred from the sample.
Additionally, the sample confirms that `email` and `createdAt` are plain strings, but a real API might return different formats. Furthermore, empty arrays are represented as `z.array(z.null())` in the generated schema, which would reject actual items. To avoid this, you should add stricter checks based on API documentation.
The article concludes with an example of how to use the generated schema when data enters your application, such as in the `loadUser` function, which safely parses the response using the `UserSchema`. The parsed result is then checked to ensure it's valid and returned as the expected `User` type.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.