cloudflare/chanfana/write-endpoints

Claude Code and agent skill by cloudflare/chanfana

Trust tier 4
  • vendor
Source check pending

Checking that the SKILL.md file is still in the repository.

Comprehensive guide for building OpenAPI endpoints with chanfana - schema definition, request validation, CRUD operations, D1 database integration, and exception handling

Install

npx vskill@latest install cloudflare/chanfana/write-endpoints

SKILL.md

The same SKILL.md was published earlier as cloudflare/chanfana/write-endpoints.

Writing OpenAPI Endpoints with Chanfana

When to Use

Use this skill when:

  • Building OpenAPI endpoints with chanfana for Cloudflare Workers
  • Defining request/response schemas with Zod v4
  • Creating CRUD auto endpoints (Create, Read, Update, Delete, List)
  • Integrating with Cloudflare D1 databases
  • Implementing error handling with exception classes

Part 1: Fundamentals

Quick Start with Hono
typescript
import { Hono, type Context } from 'hono';
import { fromHono, OpenAPIRoute, contentJson } from 'chanfana';
import { z } from 'zod';
export type Env = {
DB: D1Database;
};
export type AppContext = Context<{ Bindings: Env }>;
class HelloEndpoint extends OpenAPIRoute {
schema = {
responses: {
"200": {
description: 'Successful response',
...contentJson(z.object({ message: z.string() })),
},
},
};
async handle(c: AppContext) {
return { message: 'Hello, Chanfana!' };
}
}
const app = new Hono<{ Bindings: Env }>();
const openapi = fromHono(app);
openapi.get('/hello', HelloEndpoint);
export default app;
Quick Start with itty-router
typescript
import { Router } from 'itty-router';
import { fromIttyRouter, OpenAPIRoute, contentJson } from 'chanfana';
import { z } from 'zod';
class HelloEndpoint extends OpenAPIRoute {
schema = {
responses: {
"200": {
description: 'Successful response',
...contentJson(z.object({ message: z.string() })),
},
},
};
async handle(request: Request, env, ctx) {
return { message: 'Hello, Chanfana!' };
}
}
const router = Router();
const openapi = fromIttyRouter(router);
openapi.get('/hello', HelloEndpoint);
router.all('*', () => new Response("Not Found.", { status: 404 }));
export const fetch = router.handle;
Schema Definition

Define request validation for body, query, params, and headers:

typescript
import { OpenAPIRoute, contentJson } from 'chanfana';
import { z } from 'zod';
class CreateUserEndpoint extends OpenAPIRoute {
schema = {
request: {
body: contentJson(z.object({
username: z.string().min(3).max(20),
password: z.string().min(8),
email: z.email(),
fullName: z.string().optional(),
})),
query: z.object({
notify: z.boolean().optional().default(true),
}),
params: z.object({
orgId: z.uuid(),
}),
headers: z.object({
'X-API-Key': z.string(),
}),
},
responses: {
"200": {
description: 'User created successfully',
...contentJson(z.object({
id: z.uuid(),
username: z.string(),
email: z.email(),
})),
},
"400": {
description: 'Validation error',
...contentJson(z.object({
success: z.literal(false),
errors: z.array(z.object({
code: z.number(),
message: z.string(),
})),
})),
},
},
};
async handle(c) {
const data = await this.getValidatedData<typeof this.schema>();
// data.body, data.query, data.params, data.headers are all typed
return { id: crypto.randomUUID(), username: data.body.username, email: data.body.email };
}
}
Zod v4 Syntax (CRITICAL)

Chanfana v3 uses Zod v4. Use the correct syntax:

typescript
// WRONG - Zod v3 syntax (deprecated)
z.string().email()
z.string().uuid()
z.string().datetime()
z.string().date()
z.string().url()
z.string().ip({ version: "v4" })
z.object({}).strict()
z.nativeEnum(MyEnum)
// CORRECT - Zod v4 syntax
z.email()
z.uuid()
z.iso.datetime()
z.iso.date()
z.url()
z.ipv4()
z.strictObject({})
z.enum(['option1', 'option2'])
Common Zod Types for APIs

Use native Zod schemas for all parameter types:

typescript
import { z } from 'zod';
// String with constraints
const nameSchema = z.string()
.min(3)
.max(50)
.describe("User's name")
.openapi({ example: 'John Doe' });
// Number with range
const priceSchema = z.number()
.min(0)
.describe('Product price')
.openapi({ example: 99.99 });
// Integer
const ageSchema = z.number()
.int()
.min(0)
.max(120)
.describe("User's age");
// Boolean with default
const isActiveSchema = z.boolean()
.default(true)
.describe('User active status');
// Date/time (ISO 8601)
const createdAtSchema = z.iso.datetime()
.describe('Creation timestamp')
.openapi({ example: '2024-01-20T10:30:00Z' });
// Date only (YYYY-MM-DD)
const birthDateSchema = z.iso.date()
.describe('Birth date')
.openapi({ example: '1990-05-15' });
// Email, UUID
const emailSchema = z.email().describe('Email address');
const userIdSchema = z.uuid().describe('User ID');
// Enumeration
const statusSchema = z.enum(['pending', 'processing', 'shipped', 'delivered'])
.default('pending')
.describe('Order status');
// Array
const tagsSchema = z.array(z.string()).openapi({
description: 'Tags',
});
// Object
const addressSchema = z.object({
street: z.string().describe('Street address'),
city: z.string().describe('City'),
zipCode: z.string().describe('Zip code'),
});
// Regex pattern
const phoneSchema = z.string()
.regex(/^\+?[1-9]\d{1,14}$/, 'Invalid phone number format')
.describe('Phone number');
// IP addresses
const ipv4Schema = z.ipv4();
const ipv6Schema = z.ipv6();
const ipSchema = z.union([z.ipv4(), z.ipv6()]);
// Hostname (regex pattern)
const hostnameSchema = z.string().regex(
/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/
);
Validated Data Access

Always use await with getValidatedData():

typescript
class MyEndpoint extends OpenAPIRoute {
async handle(c) {
// CORRECT - with await and type annotation
const data = await this.getValidatedData<typeof this.schema>();
// Type-safe access
const username = data.body.username;
const page = data.query.page;
const userId = data.params.userId;
const apiKey = data.headers['X-API-Key'];
return { success: true };
}
}
Using getUnvalidatedData() for Partial Updates

In Zod v4, optional fields with .default() always have values in validated data. Use getUnvalidatedData() to detect what was actually sent:

typescript
class UpdateUser extends OpenAPIRoute {
schema = {
request: {
body: contentJson(z.object({
name: z.string().optional(),
status: z.enum(['active', 'inactive']).default('active'),
})),
},
};
async handle() {
const validated = await this.getValidatedData<typeof this.schema>();
// validated.body.status is 'active' even if not sent
const raw = await this.getUnvalidatedData();
// raw.body = {} if nothing was sent
// Check what was actually sent
const updates: Record<string, any> = {};
if ('name' in raw.body) updates.name = validated.body.name;
if ('status' in raw.body) updates.status = validated.body.status;
return { updated: updates };
}
}
Route Middleware and Validated Data in Middleware (Hono only)

Hono middleware can be placed before the endpoint class. To read the endpoint's validated data in middleware, add the opt-in chanfanaValidator() marker: middleware after it get typed c.req.valid('json' | 'query' | 'param' | 'header') (Zod output, coerced and defaulted), and the endpoint reuses that data instead of validating twice.

typescript
import { chanfanaValidator } from 'chanfana';
openapi.post('/users', authMiddleware, CreateUser); // plain middleware, typed like Hono
openapi.post(
'/users',
authMiddleware, // before the marker: no c.req.valid()
chanfanaValidator(), // validates against CreateUser's schema, same 400/7001 on failure
async (c, next) => {
const { email } = c.req.valid('json'); // typed from CreateUser.schema
return next();
},
CreateUser, // must come last, after the marker
);

Rules:

  • fromHono() only. Using it with fromIttyRouter(), in app.use(), twice in a route, or in a route that doesn't end with a single endpoint class throws at registration.
  • No 'json' on get() routes; on all() routes it is typed T | undefined (GET/HEAD requests have no body).
  • Typed for up to 5 middleware before the endpoint; longer chains are untyped.
  • c.req.valid() is only typed when schema has a literal type (not annotated OpenAPIRouteSchema, not built in getSchema()); otherwise it is any.
  • The endpoint's handle() context is not typed from the chain. Middleware that mutate c.req.valid() objects change what the endpoint sees.

Part 2: CRUD Auto Endpoints

Meta Object Definition

All auto endpoints require a _meta property:

typescript
import { z } from 'zod';
// Define the model schema
const UserSchema = z.object({
id: z.uuid(),
username: z.string().min(3).max(20),
email: z.email(),
role: z.enum(['user', 'admin']),
createdAt: z.iso.datetime(),
});
// Define the meta object
const userMeta = {
model: {
schema: UserSchema, // Required: Zod schema for the model
primaryKeys: ['id'], // Required: Array of primary key fields
tableName: 'users', // Required for D1 endpoints
serializer: (user: any) => { // Optional: Transform output
const { passwordHash, ...safe } = user;
return safe;
},
serializerSchema: UserSchema.omit({ passwordHash: true }), // Optional: Schema for serialized output
},
pathParameters: ['id'], // Optional: Explicit path params for nested routes
tags: ['Users'], // Optional: OpenAPI tags for grouping operations
};
CreateEndpoint
typescript
import { CreateEndpoint, type O } from 'chanfana';
class CreateUser extends CreateEndpoint {
_meta = userMeta;
// Optional: Pre-processing hook
async before(data: O<typeof this._meta>): Promise<O<typeof this._meta>> {
return {
...data,
id: crypto.randomUUID(),
createdAt: new Date().toISOString(),
};
}
// Required: Create logic
async create(data: O<typeof this._meta>) {
await db.users.insert(data);
return data;
}
// Optional: Post-processing hook
async after(data: O<typeof this._meta>): Promise<O<typeof this._meta>> {
await sendWelcomeEmail(data.email);
return data;
}
}
// Register route
openapi.post('/users', CreateUser);
ReadEndpoint
typescript
import { ReadEndpoint, type Filters, type O } from 'chanfana';
class GetUser extends ReadEndpoint {
_meta = userMeta;
async before(filters: Filters): Promise<Filters> {
// Pre-fetch validation
return filters;
}
async fetch(filters: Filters): Promise<O<typeof this._meta> | null> {
const userId = filters.filters[0].value;
return await db.users.findById(userId);
}
async after(data: O<typeof this._meta>): Promise<O<typeof this._meta>> {
// Post-fetch processing
return data;
}
}
// Register route with path parameter
openapi.get('/users/:id', GetUser);
ListEndpoint
typescript
import { ListEndpoint, type ListFilters, type ListResult, type O } from 'chanfana';
class ListUsers extends ListEndpoint {
_meta = userMeta;

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files. Certified 23 Sep 2026.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
767
Repository forks
70
Repository npm downloads, 7 days
65,154
7-day trend score
58

Stars and forks are for the whole GitHub repository, not this skill alone. Downloads are for the repository's npm package. Refreshed 1 May 2026, 6 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill CERTIFIED badge
[![vskill CERTIFIED](https://verified-skill.com/api/v1/skills/cloudflare/chanfana/write-endpoints/badge)](https://verified-skill.com/skills/cloudflare/chanfana/write-endpoints)

Something wrong with this skill or its page? Tell us.