api-patterns
This skill provides API route patterns and conventions for the fitness app. Use when creating or modifying API routes, handling authentication, validating requests, or implementing error handling.
What this skill does
# API Route Patterns & Best Practices
This skill provides comprehensive patterns for building API routes in the fitness application using Nuxt server routes.
## Core Principles
**Separation of Concerns**: All database logic MUST be in `/server/database/queries/`. Never use `useDB()` directly in API routes.
**Return Data Directly**: Don't wrap successful responses in `{ success: true, data: ... }`.
**Custom Validation**: Always use validation helpers from `server/utils/bodyValidation.ts` instead of Nuxt's built-in functions.
## API Route Structure
Every API route follows this pattern:
```typescript
import { z } from 'zod'
import { queryUserWorkouts } from '~~/server/database/queries/workouts'
import { validateBody, validateParams, validateQuery } from '~~/server/utils/bodyValidation'
// 1. Define validation schemas locally
const paramsSchema = z.object({
id: z.uuid(),
})
const bodySchema = z.object({
name: z.string().min(1).max(100),
description: z.string().max(500).optional(),
})
const querySchema = z.object({
limit: z.coerce.number().int().min(1).max(100).default(20),
})
// 2. Define event handler
export default defineEventHandler(async (event) => {
// 3. Authenticate user
const { user } = await requireUserSession(event)
// 4. Validate request data
const { id } = await validateParams(event, paramsSchema)
const body = await validateBody(event, bodySchema)
const query = await validateQuery(event, querySchema)
// 5. Use query functions (never useDB() directly)
const workouts = await queryUserWorkouts(user.id, query.limit)
// 6. Return data directly (no wrapper)
return workouts
})
```
## Authentication
Use `requireUserSession` to get the authenticated user:
```typescript
export default defineEventHandler(async (event) => {
// Throws 401 if not authenticated
const { user, session } = await requireUserSession(event)
// user.id is available for queries
const workouts = await queryUserWorkouts(user.id)
return workouts
})
```
**Key points:**
- Automatically throws 401 Unauthorized if no session
- Returns both `user` and `session` objects
- Destructure to get only what you need: `const { user } = await requireUserSession(event)`
## Request Validation
**Always use custom validation helpers** from `server/utils/bodyValidation.ts`:
### validateBody
Validate request body:
```typescript
const bodySchema = z.object({
name: z.string().min(1).max(100),
weight: z.coerce.number().positive(),
sets: z.coerce.number().int().min(1),
})
export default defineEventHandler(async (event) => {
const body = await validateBody(event, bodySchema)
// body is typed and validated
})
```
### validateParams
Validate route parameters:
```typescript
// Route: /api/workouts/[id].ts
const paramsSchema = z.object({
id: z.uuid(),
})
export default defineEventHandler(async (event) => {
const { id } = await validateParams(event, paramsSchema)
// id is validated as UUID
})
```
### validateQuery
Validate query parameters:
```typescript
// Route: /api/workouts?status=active&limit=20
const querySchema = z.object({
status: z.enum(['active', 'completed']).optional(),
limit: z.coerce.number().int().min(1).max(100).default(20),
page: z.coerce.number().int().min(1).default(1),
})
export default defineEventHandler(async (event) => {
const query = await validateQuery(event, querySchema)
// query.limit and query.page have defaults
})
```
**Important:** Use `z.coerce.number()` for numeric query/body params as they come as strings.
## Response Handling
### Success Responses
Return data directly without wrapping:
```typescript
// ✅ Correct
export default defineEventHandler(async (event) => {
const workouts = await queryUserWorkouts(userId)
return workouts // Return array directly
})
// ❌ Wrong: Don't wrap
export default defineEventHandler(async (event) => {
const workouts = await queryUserWorkouts(userId)
return { success: true, data: workouts } // Don't do this
})
```
### Error Responses
Use `createError` for error responses:
```typescript
export default defineEventHandler(async (event) => {
const { id } = await validateParams(event, paramsSchema)
const workout = await queryWorkoutById(id)
if (!workout) {
throw createError({
statusCode: 404,
statusMessage: 'Workout not found'
})
}
return workout
})
```
**Common status codes:**
- `400` - Bad Request (validation errors)
- `401` - Unauthorized (not authenticated)
- `403` - Forbidden (authenticated but not authorized)
- `404` - Not Found
- `409` - Conflict (e.g., duplicate resource)
- `422` - Unprocessable Entity (semantic validation errors)
- `500` - Internal Server Error
## Complete CRUD Examples
### POST - Create Resource
```typescript
// server/api/workouts/index.post.ts
import { z } from 'zod'
import { createWorkout } from '~~/server/database/queries/workouts'
import { validateBody } from '~~/server/utils/bodyValidation'
const bodySchema = z.object({
name: z.string().min(1).max(100),
description: z.string().max(500).optional(),
isPublic: z.boolean().default(false),
exercises: z.array(z.uuid()).min(1),
})
export default defineEventHandler(async (event) => {
const { user } = await requireUserSession(event)
const body = await validateBody(event, bodySchema)
const workout = await createWorkout({
...body,
userId: user.id,
})
return workout
})
```
### GET - Read Resource
```typescript
// server/api/workouts/[id].get.ts
import { z } from 'zod'
import { getWorkoutById } from '~~/server/database/queries/workouts'
import { validateParams } from '~~/server/utils/bodyValidation'
const paramsSchema = z.object({
id: z.uuid(),
})
export default defineEventHandler(async (event) => {
const { user } = await requireUserSession(event)
const { id } = await validateParams(event, paramsSchema)
const workout = await getWorkoutById(id, user.id)
// getWorkoutById throws 404 if not found
return workout
})
```
### GET - List Resources
```typescript
// server/api/workouts/index.get.ts
import { z } from 'zod'
import { queryUserWorkouts } from '~~/server/database/queries/workouts'
import { validateQuery } from '~~/server/utils/bodyValidation'
const querySchema = z.object({
status: z.enum(['active', 'completed']).optional(),
limit: z.coerce.number().int().min(1).max(100).default(20),
offset: z.coerce.number().int().min(0).default(0),
})
export default defineEventHandler(async (event) => {
const { user } = await requireUserSession(event)
const query = await validateQuery(event, querySchema)
const workouts = await queryUserWorkouts(user.id, query)
return workouts
})
```
### PATCH - Update Resource
```typescript
// server/api/workouts/[id].patch.ts
import { z } from 'zod'
import { updateWorkout } from '~~/server/database/queries/workouts'
import { validateParams, validateBody } from '~~/server/utils/bodyValidation'
const paramsSchema = z.object({
id: z.uuid(),
})
const bodySchema = z.object({
name: z.string().min(1).max(100).optional(),
description: z.string().max(500).optional(),
isPublic: z.boolean().optional(),
}).refine(
data => Object.keys(data).length > 0,
{ message: 'At least one field must be provided' }
)
export default defineEventHandler(async (event) => {
const { user } = await requireUserSession(event)
const { id } = await validateParams(event, paramsSchema)
const body = await validateBody(event, bodySchema)
const workout = await updateWorkout(id, user.id, body)
// updateWorkout throws 404 if not found
return workout
})
```
### DELETE - Delete Resource
```typescript
// server/api/workouts/[id].delete.ts
import { z } from 'zod'
import { deleteWorkout } from '~~/server/database/queries/workouts'
import { validateParams } from '~~/server/utils/bodyValidation'
const paramsSchema = z.object({
id: z.uuid(),
})
export default defineEventHandler(async (event) => {
const { user } = await requireUserSession(event)
const { id } Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.