You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Enhance API documentation and validation using Zod
- Added automatic validation with Zod for Fastify routes, eliminating manual validation.
- Updated API documentation for `/api/db/status`, `/api/db/setup`, and user registration endpoints to include detailed descriptions, request bodies, and response schemas.
- Implemented Zod schemas for request and response validation in `loginEmail`, `registerEmail`, and `dbSetup` routes.
- Improved error handling and response structures for better clarity and consistency.
- Removed redundant manual validation logic from route handlers, relying on Fastify's built-in validation.
Copy file name to clipboardExpand all lines: services/backend/API_DOCUMENTATION.md
+89-17Lines changed: 89 additions & 17 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -90,14 +90,19 @@ To add OpenAPI documentation to your routes, define your request body and respon
90
90
91
91
Make sure you have `zod` and `zod-to-json-schema` installed in your backend service.
92
92
93
+
### Recommended Approach: Automatic Validation with Zod
94
+
95
+
The power of Zod lies in providing **automatic validation** through Fastify's schema system. This approach eliminates manual validation and leverages Zod's full validation capabilities.
**Note**: Older examples in this document (like the "Logout Route Documentation" below) might still show manually crafted JSON schemas. The recommended approach is now to use Zod with `zod-to-json-schema` as shown above for better type safety and maintainability.
199
+
✅ **Do trust Fastify's automatic validation:**
200
+
```typescript
201
+
// GOOD: Trust the validation - if handler runs, data is valid
202
+
const { name, count, type } =request.body; // Already validated by Fastify
If validation fails, Fastify automatically returns a 400 error **before** your handler runs.
217
+
218
+
### Real-World Examples
219
+
220
+
See these files for complete examples of proper Zod validation:
221
+
-`src/routes/db/setup.ts` - Database setup with enum validation
222
+
-`src/routes/db/status.ts` - Simple GET endpoint with response schemas
223
+
-`src/routes/auth/loginEmail.ts` - Login with required string fields
224
+
-`src/routes/auth/registerEmail.ts` - Registration with complex validation rules
225
+
226
+
**Note**: Older examples in this document (like the "Logout Route Documentation" below) might still show manually crafted JSON schemas. The recommended approach is now to use Zod with automatic Fastify validation as shown above.
0 commit comments