Skip to content

Response Schemas

Yelix provides zodToResponseSchema to convert Zod schemas into OpenAPI response schemas automatically:

import { YelixHono, openapi, zodToResponseSchema } from '@yelix/hono';
import { z } from 'zod';
const app = new YelixHono();
app.get(
'/users/:id',
openapi({
summary: 'Get User by ID',
responses: {
200: {
description: 'User retrieved successfully',
content: zodToResponseSchema(
z.object({
id: z.uuid(),
name: z.string(),
email: z.email(),
createdAt: z.date(),
})
),
},
},
}),
(c) => {
return c.json({
id: '123e4567-e89b-12d3-a456-426614174000',
name: 'John Doe',
email: 'john@example.com',
createdAt: new Date(),
});
}
);

Document different response codes for the same endpoint:

app.get(
'/users/:id',
openapi({
summary: 'Get User by ID',
responses: {
200: {
description: 'User retrieved successfully',
content: zodToResponseSchema(
z.object({
id: z.uuid(),
name: z.string(),
email: z.email(),
})
),
},
404: {
description: 'User not found',
content: zodToResponseSchema(
z.object({
error: z.string(),
message: z.string(),
})
),
},
500: {
description: 'Internal server error',
content: zodToResponseSchema(
z.object({
error: z.string(),
message: z.string(),
})
),
},
},
}),
(c) => { /* ... */ }
);

You can use all Zod features for complex schemas:

import { z } from 'zod';
// Array responses
zodToResponseSchema(
z.array(
z.object({
id: z.string(),
name: z.string(),
})
)
);
// Nested objects
zodToResponseSchema(
z.object({
user: z.object({
id: z.string(),
name: z.string(),
profile: z.object({
bio: z.string().optional(),
avatar: z.string().url().optional(),
}),
}),
metadata: z.object({
total: z.number(),
page: z.number(),
}),
})
);
// Optional fields
zodToResponseSchema(
z.object({
id: z.string(),
name: z.string(),
email: z.string().email().optional(),
phone: z.string().optional(),
})
);
// Union types
zodToResponseSchema(
z.union([
z.object({ type: 'success', data: z.any() }),
z.object({ type: 'error', message: z.string() }),
])
);

You can add descriptions to your schema fields for better documentation:

zodToResponseSchema(
z.object({
id: z.string().describe('Unique user identifier'),
name: z.string().describe('User full name'),
email: z.string().email().describe('User email address'),
role: z.enum(['admin', 'user', 'guest']).describe('User role'),
})
);