How to generate a zod schema for api request body validation
- Step 1Create a sample request body — Build the most complete valid request body JSON — include all optional fields populated with realistic values. This produces a schema that covers the full input shape.
- Step 2Generate the Zod schema — Paste the request body JSON and convert. The output z.object() schema covers the full request body shape.
- Step 3Add constraints and mark optional fields — Add type constraints: string →’ .min(1).max(255), id →’ .uuid(), email →’ .email(), status →’ .enum(['active', 'inactive']). Mark fields optional: .optional() for fields that may be absent from the request.
- Step 4Add to Next.js Route Handler — export async function POST(request: Request) { const body = await request.json(); const parsed = RequestSchema.safeParse(body); if (!parsed.success) { return Response.json({ errors: parsed.error.flatten() }, { status: 400 }); } const data = parsed.data; ... }.
Frequently asked questions
Should I use parse() or safeParse() in API route handlers?+
Use safeParse() in API route handlers so you can return a structured 400 error response when validation fails. schema.parse() throws a ZodError exception which, if unhandled, produces a 500 response. safeParse() returns { success, data, error } so you control the error response format.
How do I return Zod validation errors in a useful API response format?+
Use error.flatten() which returns { fieldErrors: { field: [message] }, formErrors: [message] }. Or use error.format() for a nested error tree. The flattened format is easiest to consume in client-side error display: fieldErrors.email[0] gives the first email validation error message.
Is the API request sample transmitted to JAD Apps?+
No. Schema generation runs entirely in your browser. API request bodies are never transmitted to JAD Apps servers.
Privacy first
Conversion runs locally in your browser. No file is uploaded — only metadata counters are saved for signed-in dashboard stats.