# API Design Patterns — {{projectName}}

> **Scope:** Backend API development | **Loaded On-Demand**

---

## RESTful Conventions

### URL Structure
{{#if apiUrlStructure}}
{{apiUrlStructure}}
{{else}}
- Use kebab-case for resource names: `/api/v1/user-profiles`
- Use plural for collections: `/api/v1/users` (not `/api/v1/user`)
- Nest resources logically: `/api/v1/users/{userId}/posts`
{{/if}}

### HTTP Methods
{{#if httpMethods}}
{{#each httpMethods}}
- **{{this.method}}** {{this.usage}}
{{/each}}
{{else}}
- **GET** — Retrieve resources (no side effects)
- **POST** — Create new resources
- **PATCH** — Partial updates (preferred over PUT)
- **PUT** — Full replacement (rarely used)
- **DELETE** — Resource deletion
{{/if}}

### Response Format
{{#if responseFormat}}
{{responseFormat}}
{{else}}
Always return consistent JSON structure:

```json
{
  "data": { ... },
  "meta": {
    "page": 1,
    "perPage": 20,
    "total": 100
  },
  "errors": null
}
```
{{/if}}

---

## Error Handling

### Error Response Structure
```json
{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "User-friendly message",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format"
      }
    ],
    "requestId": "req_abc123"
  }
}
```

### HTTP Status Codes
{{#if errorCodes}}
{{#each errorCodes}}
- **{{this.code}}** — {{this.description}}
{{/each}}
{{else}}
- **200** — Success
- **201** — Created
- **204** — No Content
- **400** — Bad Request (validation errors)
- **401** — Unauthorized (not logged in)
- **403** — Forbidden (logged in, no permission)
- **404** — Not Found
- **409** — Conflict (duplicate, state mismatch)
- **422** — Unprocessable Entity
- **429** — Too Many Requests (rate limit)
- **500** — Internal Server Error
- **503** — Service Unavailable
{{/if}}

### Error Codes Naming
{{#if errorNaming}}
Use {{errorNaming}}
{{else}}
Use SCREAMING_SNAKE_CASE for error codes:
- `VALIDATION_FAILED`
- `AUTHENTICATION_REQUIRED`
- `RATE_LIMIT_EXCEEDED`
- `RESOURCE_NOT_FOUND`
{{/if}}

---

## Authentication & Authorization

{{#if authPatterns}}
{{authPatterns}}
{{else}}
### Authentication
- Use JWT tokens with httpOnly cookies
- Include `expiresIn` claim
- Refresh token endpoint: `POST /api/v1/auth/refresh`

### Authorization
- Check permissions at route level
- Use role-based access control (RBAC)
- Return 403 for permission errors (not 401)
{{/if}}

---

## Pagination

### Standard Pagination
{{#if pagination}}
{{pagination}}
{{else}}
Default: page-based pagination
```
GET /api/v1/users?page=1&perPage=20
```

Response:
```json
{
  "data": [...],
  "meta": {
    "page": 1,
    "perPage": 20,
    "totalPages": 5,
    "total": 100
  }
}
```
{{/if}}

---

## Rate Limiting

{{#if rateLimiting}}
{{rateLimiting}}
{{else}}
- Standard: 100 requests/minute per IP
- Authenticated: 1000 requests/minute per user
- Headers returned:
  - `X-RateLimit-Limit`
  - `X-RateLimit-Remaining`
  - `X-RateLimit-Reset`
{{/if}}

---

## Versioning

{{#if apiVersioning}}
{{apiVersioning}}
{{else}}
- URL-based versioning: `/api/v1/`, `/api/v2/`
- Maintain backward compatibility for at least one major version
- Document deprecation timeline
{{/if}}

---

## Validation

{{#if validationRules}}
{{validationRules}}
{{else}}
### Request Validation
- Validate all inputs at handler boundary
- Return detailed field-level errors
- Use Zod or similar schema validation

### Response Validation
- Validate contracts against OpenAPI schema
- Type-safe client generation from OpenAPI
{{/if}}

---

## OpenAPI Contract Requirements

{{#if openApiRequirements}}
{{openApiRequirements}}
{{else}}
Every API must have:
1. OpenAPI 3.1 spec in `/contracts/`
2. All endpoints documented with:
   - Summary and description
   - Request/response schemas
   - Error responses
   - Authentication requirements
3. Auto-generated TypeScript types
4. Example requests/responses
{{/if}}

---

> **Token Budget:** ~1000 tokens max
> **Loaded On-Demand** — Only when working on API code
