betting-brain-v3 / rules
Cursor rule8 starsChanged 14 months agoMITView on GitHub
API endpoint patterns and request handling conventions
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 4,373 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository27 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- .cursor/rules/99-floor.mdcCursor rule
- .cursor/rules/ai-friendly-testing.mdcCursor rule
- .cursor/rules/analytics-stub-api.mdcCursor rule
- .cursor/rules/analytics-testing.mdcCursor rule
- .cursor/rules/browser-extension.mdcCursor rule
- .cursor/rules/bun-runtime.mdcCursor rule
- .cursor/rules/cache-optimization.mdcCursor rule
- .cursor/rules/ci-integration.mdcCursor rule
- .cursor/rules/ci-patterns.mdcCursor rule
- .cursor/rules/cloudflare-infrastructure.mdcCursor rule
- .cursor/rules/cloudflare-workers.mdcCursor rule
- .cursor/rules/code-searchability.mdcCursor rule
- .cursor/rules/coverage-thresholds.mdcCursor rule
- .cursor/rules/database-patterns.mdcCursor rule
- .cursor/rules/documentation.mdcCursor rule
- .cursor/rules/endpoint-routing.mdcCursor rule
- .cursor/rules/file-naming.mdcCursor rule
- .cursor/rules/mcp-integration.mdcCursor rule
- .cursor/rules/process-management.mdcCursor rule
- .cursor/rules/production-security.mdcCursor rule
- .cursor/rules/quality-standards.mdcCursor rule
- .cursor/rules/root-organization.mdcCursor rule
- .cursor/rules/security-patterns.mdcCursor rule
- .cursor/rules/testing.mdcCursor rule
- .cursor/rules/testing-patterns.mdcCursor rule
- .cursor/rules/test-setup-patterns.mdcCursor rule
The file
We split this api-patterns.mdc into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 243
When using createErrorResponse(), format is:
≈ “Common” is an estimate: at least 1 in 5 of the 7,324 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
version: "5.0.0"
scope: ["typescript", "javascript"]
alwaysApply: true
description: "API endpoint patterns and request handling conventions"
lastUpdated: "2025-10-08"
dependencies: ["quality-standards", "database-patterns", "endpoint-routing", "bun-runtime"]
---
## 🔍 Code Searchability Patterns
### Find api-patterns Issues with ast-grep
```bash
# Find async function $NAME(request: Request, env: Env, requestId: string)
# Find return createJSONResponse($$$)
# Find return createErrorResponse($$$)
# Find generateRequestId()
# Find createLogger($$$)
ast-grep --pattern 'async function $NAME(request: Request, env: Env, requestId: string)' src/
ast-grep --pattern 'return createJSONResponse($$$)' src/
ast-grep --pattern 'return createErrorResponse($$$)' src/
ast-grep --pattern 'generateRequestId()' src/
ast-grep --pattern 'createLogger($$$)' src/
sg -p 'async' src/
sg -p 'return' src/
sg -p 'return' src/
sg -p 'generateRequestId()' src/
sg -p 'createLogger($$$)' src/
```
### api-patterns Discovery Commands
```bash
sg search "async function" src/api/
sg search "createJSONResponse" src/
sg search "generateRequestId" src/
sg search "createLogger" src/
```
### Search Examples
```bash
# Find all API endpoint handlers
sg search 'async' src/
# Find JSON response patterns
sg search 'return' src/
# Find request ID generation
sg search 'return' src/
# Find logging patterns
sg search 'generateRequestId()' src/
```
## Error Handling Patterns
### Using Error Classes
**Location:** `src/utils/error-handler.ts`
```typescript
import { Errors, createErrorResponse } from '../utils/error-handler';
// In endpoint handler
try {
// Validation error
if (!isValid) {
throw Errors.validationError(['Field is required']);
}
// Not found
if (!record) {
throw Errors.notFound('Event');
}
// Database error
if (queryFailed) {
throw Errors.databaseError('Query failed: ' + error.message);
}
// Success response
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
return createErrorResponse(error, requestId, url.pathname);
}
```
### Error Types
```typescript
// Client errors (4xx)
Errors.badRequest(message, details?) // 400
Errors.unauthorized(message?) // 401
Errors.forbidden(message?) // 403
Errors.notFound(resource?) // 404
Errors.validationError(errors[]) // 400
Errors.rateLimit(message?) // 429
// Server errors (5xx)
Errors.databaseError(message) // 500
Errors.serviceUnavailable(message?) // 503
Errors.timeout(message?) // 504
```
### Async Handler Wrapper
```typescript
import { asyncHandler } from '../utils/error-handler';
// Automatically catches and formats errors
export const myEndpoint = asyncHandler(async (request, env, ctx) => {
// Your code here
// Any thrown errors will be caught and formatted automatically
return new Response(JSON.stringify(result));
});
```
---
## API Endpoint Patterns
### REST API Structure
**Location:** `src/api/routes.ts`
```typescript
import { generateRequestId, CORS_HEADERS, createOPTIONSResponse } from '../utils/request';
export async function handleAPIRoute(
request: Request,
env: Env,
ctx: ExecutionContext
): Promise<Response> {
const requestId = generateRequestId();
const url = new URL(request.url);
const path = url.pathname.replace('/api', '');
// Handle OPTIONS preflight
if (request.method === 'OPTIONS') {
return createOPTIONSResponse();
}
try {
// Route to endpoint
switch (path) {
case '/events':
return await getEvents(request, env, requestId);
// ... more routes
default:
throw Errors.notFound('API endpoint');
}
} catch (error) {
return createErrorResponse(error, requestId, path);
}
}
```
### Endpoint Handler Pattern
```typescript
import {
normalizeD1Result,
createJSONResponse,
getQueryParamNumber
} from '../utils/request';
import { createLogger } from '../utils/logger';
async function getMyEndpoint(
request: Request,
env: Env,
requestId: string
): Promise<Response> {
const logger = createLogger(request);
// 1. Validate environment
validateEnv(env, ['ANALYTICS']);
// 2. Validate input
const validation = validateQueryParams(url, [
Validators.agentID(),
Validators.limit(500)
]);
if (!validation.valid) {
return validationErrorResponse(validation.errors, requestId);
}
const { agentID, limit } = validation.sanitized!;
// 3. Query database
const result = await env.ANALYTICS.prepare(`
SELECT * FROM table WHERE aid = ? LIMIT ?
`).bind(agentID, limit).all();
const data = normalizeD1Result<MyType>(result);
// 4. Log success
logger.info('query_completed', {
requestId,
recordCount: data.length
});
// 5. Return response
return createJSONResponse({
data,
total: data.length,
requestId,
timestamp: new Date().toISOString()
});
}
```
---
## Response Patterns
### Success Response
```typescript
return new Response(JSON.stringify({
// Your data
events: [...],
customers: [...],
// Metadata (always include)
requestId: requestId,
timestamp: new Date().toISOString(),
// Pagination (if applicable)
total: total,
limit: limit,
offset: offset
}), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
});
```
### Error Response (Automatic)
When using `createErrorResponse()`, format is:
```json
{
"error": "ERROR_CODE",
"code": "ERROR_CODE",
"message": "Human-readable message",
"details": { /* optional */ },
"requestId": "abc123",
"timestamp": "2025-10-07T14:45:00.000Z",
"path": "/api/endpoint"
}
```
---
## CORS Patterns
### Standard CORS Headers
```typescript
import { CORS_HEADERS, createOPTIONSResponse, createJSONResponse } from '../utils/request';
// Handle OPTIONS preflight
if (request.method === 'OPTIONS') {
return createOPTIONSResponse();
}
// Include in all responses (automatic with createJSONResponse)
return createJSONResponse({ data });
// Or manually
return new Response(data, { headers: { ...CORS_HEADERS } });
```
---
## Request ID Tracking
### Generate and Use
```typescript
import { generateRequestId, getRequestId } from '../utils/request';
import { createLogger } from '../utils/logger';
// Generate at start of request
const requestId = generateRequestId();
// Or extract from headers
const requestId = getRequestId(request);
// Use structured logging
const logger = createLogger(request);
logger.info('request_received', { requestId });
logger.info('request_completed', { requestId });
logger.error('request_failed', { requestId }, error);
// Include in response (automatic with createJSONResponse)
return createJSONResponse({
...data,
requestId
});
// Include in errors
return createErrorResponse('Error message', 500, 'ERROR_CODE', requestId);
```
---
## Database Query Patterns
### Type-safe D1 Queries
```typescript
import { normalizeD1Result } from '../utils/request';
// Query with type conversion
const result = await env.ANALYTICS.prepare(`
SELECT eid, mt, ts
FROM line_movements
WHERE eid = ?
LIMIT ?
`).bind(eventID, limit).all();
// Normalize results with proper typing
type Movement = {
eid: string;
mt: string;
ts: string;
};
const movements = normalizeD1Result<Movement>(result);
```
### Parameterized Queries (Prevent SQL Injection)
```typescript
// ✅ CORRECT: Parameterized
const result = await env.ANALYTICS.prepare(`
SELECT * FROM table WHERE id = ? AND type = ?
`).bind(id, type).all();
// ❌ WRONG: String interpolation
const result = await env.ANALYTICS.prepare(`
SELECT * FROM table WHERE id = '${id}' AND type = '${type}'
`).all();
```
---
## Testing Patterns
### Testing Endpoints
```bash
# Local testing
bun run dev
# Test with curl
curl "http://localhost:8787/api/events?sport=NFL&limit=10"
# Test with validation error
curl "http://localhost:8787/api/events?limit=9999"
```
### Testing Validation
```typescript
import { validateInput, Validators } from './validation';
const result = validateInput({ agentID: 'test_123' }, [
Validators.agentID(true)
]);
expect(result.valid).toBe(true);
expect(result.sanitized.agentID).toBe('test_123');
```
---
## Best Practices
### 1. Always Validate Input
```typescript
// Every endpoint should validate
const validation = validateQueryParams(url, [...]);
if (!validation.valid) {
return validationErrorResponse(validation.errors, requestId);
}
```
### 2. Always Handle Errors
```typescript
// Use try-catch or asyncHandler
try {
// Your code
} catch (error) {
return createErrorResponse(error, requestId, path);
}
```
### 3. Always Include CORS
```typescript
import { CORS_HEADERS, createJSONResponse } from '../utils/request';
// Use createJSONResponse (includes CORS automatically)
return createJSONResponse({ data });
// Or manually
headers: { ...CORS_HEADERS }
```
### 4. Always Track Requests
```typescript
import { generateRequestId } from '../utils/request';
// Generate requestId at start
const requestId = generateRequestId();
// Include in response (automatic with createJSONResponse)
return createJSONResponse({ ...data, requestId });
```
### 5. Always Log Appropriately
```typescript
import { createLogger } from '../utils/logger';
const logger = createLogger(request);
// Start of request
logger.info('request_received', { method, path });
// Success
logger.info('query_completed', { recordCount: count });
// Error
logger.error('query_failed', { errorCode: error.code }, error);
```
---
## Related Documentation
- **[REST_API_REFERENCE.md](mdc:docs/REST_API_REFERENCE.md)** - Complete API reference
- **[API_ENHANCEMENT_SUMMARY.md](mdc:docs/API_ENHANCEMENT_SUMMARY.md)** - Enhancement overview
- **[error-handler.ts](mdc:src/utils/error-handler.ts)** - Error handling utilities
- **[validation.ts](mdc:src/utils/validation.ts)** - Validation utilities
- **[routes.ts](mdc:src/api/routes.ts)** - API route implementations
## Related Rules
- [Quality Standards](mdc:.cursor/rules/quality-standards.mdc) - Code quality standards ⭐ **NEW**
- [Endpoint Routing](mdc:.cursor/rules/endpoint-routing.mdc) - Endpoint patterns
- [Security Patterns](mdc:.cursor/rules/security-patterns.mdc) - Security considerations
- [Database Patterns](mdc:.cursor/rules/database-patterns.mdc) - Database query patterns
- [Cloudflare Workers](mdc:.cursor/rules/cloudflare-workers.mdc) - Workers-specific patterns
## Related Documentation
- [docs/QUALITY_STANDARDS.md](mdc:docs/QUALITY_STANDARDS.md) - Complete quality guide ⭐ **NEW**
- [src/shared/constants.ts](mdc:src/shared/constants.ts) - All constants ⭐ **NEW**
- [src/utils/request.ts](mdc:src/utils/request.ts) - Request utilities ⭐ **NEW**
- [src/utils/logger.ts](mdc:src/utils/logger.ts) - Logging utilities ⭐ **NEW**
---
**Status:** Production patterns established
**Last Updated:** 2025-10-08
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

