Data Validation with APIs
Learning objectives
- You know how to perform data validation with APIs.
Validation in APIs does not differ from data validation in general. In practice, when providing an API to which users can POST data, we can use the same validation approach as discussed previously. Early on, in the chapter on Data Validation, we used the following example for validating form data.
import { Eta } from "https://deno.land/x/eta@v3.4.0/src/index.ts";
import { Hono } from "https://deno.land/x/hono@v3.12.11/mod.ts";
import { z } from "https://deno.land/x/zod@v3.22.4/mod.ts";
const eta = new Eta({ views: "templates" });
const validator = z.object({
email: z.string().email(),
yearOfBirth: z.coerce.number().min(1900).max(2030),
});
const app = new Hono();
app.get("/", (c) => c.html(eta.render("index.eta")));
app.post("/emails", async (c) => {
const body = await c.req.json();
const validationResult = validator.safeParse(body);
if (!validationResult.success) {
return c.text("not ok");
}
return c.text("ok");
});
Deno.serve(app.fetch);
When validating data with APIs, we can take the same approach as before, but not we work with JSON data instead and we can omit the use of Eta templates.
import { Hono } from "https://deno.land/x/hono@v3.12.11/mod.ts";
import { z } from "https://deno.land/x/zod@v3.22.4/mod.ts";
const validator = z.object({
email: z.string().email(),
yearOfBirth: z.coerce.number().min(1900).max(2030),
});
const app = new Hono();
app.post("/emails", async (c) => {
const body = await c.req.json();
const validationResult = validator.safeParse(body);
if (!validationResult.success) {
return c.json({
validation: "fail",
errors: validationResult.error.format()
});
}
return c.json({
validation: "success"
});
});
Deno.serve(app.fetch);
With the above, we can send data to the server and receive a validation error if the data is invalid.
curl -X POST -d '{"hello":"world"}' localhost:8000/emails
{"validation":"fail","errors":{"_errors":[],"email":{"_errors":["Required"]},"yearOfBirth":{"_errors":["Expected number, received nan"]}}}
If the data is valid, we receive a success message.
curl -X POST -d '{"email":"e@mail.net", "yearOfBirth": 1990}' localhost:8000/emails
{"validation":"success"}