#validate data after using fetch

4 messages · Page 1 of 1 (latest)

next magnet
#

does convex have some utilily to validate api response using fetch api. or i have to use zod to check?

nocturne wingBOT
#

Hi @next magnet. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Convex itself does not provide a built-in utility specifically for validating data returned from a fetch API call. The core Convex validation utilities (like v.* validators) are designed for validating function arguments and database schemas within Convex, not for arbitrary API responses.

If you want to validate the shape or content of data returned from a fetch call (for example, when calling an external API), you should use a library like Zod. Zod is commonly used in the Convex ecosystem for runtime validation and type safety, and there are examples of using Zod for input validation in Convex functions, but not directly for fetch responses. You would use Zod in your own code to parse and validate the response after fetching, like so:

import { z } from "zod";

const responseSchema = z.object({
  // define your expected response shape here
  name: z.string(),
  age: z.number(),
});

const res = await fetch("<https://api.example.com/user">);
const data = await res.json();
const parsed = responseSchema.parse(data); // throws if invalid

This approach is recommended if you want to ensure the data you receive from an external API matches your expectations.

#

In summary: Convex does not have a built-in utility for validating fetch API responses; you should use Zod or a similar validation library for this purpose. This is also suggested in community discussions, where Zod is recommended for more specific or client-side validation needs beyond what Convex provides nativelyZod with TypeScript for Server-side Validation and End-to-End Types, Discord support thread: Validation of (partial) Convex-schemas.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: