Describing a Body
Part of the REST APIs section of Coddy's Node.js journey. Lesson 7 of 25.
zod is an installed package that checks values against a description you write. import { z } from 'zod' provides its schema builder, z. One description can replace repeated hand-written field checks.
A schema describes the values a request is allowed to contain. With zod, z.object lists the fields and gives each one a rule. z.string() accepts text; z.number() accepts a number.
const Book = z.object({
title: z.string(),
year: z.number(),
});Both fields are required here. The last line in exercise.js checks the object against your schema; the next lesson explains safeParse. For this first step, focus on field names and types. A later step will use the full validation result to decide what the API should return.
Challenge
EasyThis is a small practice project. Its setup is provided; edit only exercise.js.
Fill in the Task schema with a title string and a done boolean, using z.boolean(). POST /result with {"title":"Read","done":false} returns {"valid":true}. A missing title or a string done value returns {"valid":false}.
The initial GET /result uses the supplied example {"title": "Read", "done": "false"}. Use POST /result with a JSON body to try other inputs.
The empty starter schema accepts this wrong type; your completed schema must report {"valid":false} on the initial GET.
Try it yourself
import { z } from 'zod';
const Task = z.object({});
export function exercise(body) {
return { valid: Task.safeParse(body).success };
}
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST4Browsers, Versions and Config
What Is an OriginAllowing Another OriginCORSA Page That Calls the API2Validation and Errors
Validating InputPractice on your own: Express playground