---
description: Rails API Guide
applyTo: "app/controllers/api/**/*.rb"
---

# Rails API Guide

## Core Philosophy

- Design APIs for longevity and stability
- Version from the very beginning
- Keep responses consistent and predictable
- Document thoroughly and accurately
- Build APIs that developers love to use

## API Design Principles

- Follow RESTful conventions strictly
- Use standard HTTP methods appropriately
- Return meaningful status codes
- Keep endpoints focused and simple
- Design for future extensibility

## Versioning Strategy

- Version APIs from day one
- Use URL path versioning (/api/v1)
- Never break backward compatibility
- Deprecate gracefully with notices
- Document version differences clearly

## Request Handling

- Accept JSON by default
- Support content negotiation
- Validate request formats
- Handle malformed requests gracefully
- Provide clear error messages

## Response Format

- Use consistent JSON structure
- Include metadata when helpful
- Implement sparse fieldsets
- Support response filtering
- Keep payloads minimal

## Authentication Methods

- Use token-based authentication
- Implement OAuth when appropriate
- Support API keys for simple cases
- Never use session cookies for APIs
- Document authentication clearly

## Authorization Patterns

- Check permissions for every endpoint
- Use consistent authorization logic
- Return proper 401/403 status codes
- Implement role-based access
- Audit API access patterns

## Error Handling

- Return consistent error format
- Include error codes and messages
- Provide debugging information in development
- Log errors appropriately
- Handle exceptions gracefully

## Status Codes

- Use standard HTTP status codes correctly
- 200 OK for successful GET/PUT
- 201 Created for successful POST
- 204 No Content for successful DELETE
- 422 Unprocessable Entity for validation errors

## Pagination

- Always paginate list endpoints
- Use consistent pagination format
- Include total count and page info
- Support customizable page sizes
- Consider cursor-based pagination

## Rate Limiting

- Implement rate limiting from start
- Return rate limit headers
- Use progressive throttling
- Provide higher limits for authenticated users
- Document rate limits clearly

## Filtering and Sorting

- Support field filtering
- Implement sort parameters
- Allow multiple sort fields
- Use consistent parameter names
- Document available options

## Serialization

- Use Active Model Serializers or similar
- Keep serializers focused
- Support nested resources carefully
- Implement field selection
- Cache serialized responses

## Documentation

- Document every endpoint
- Include request/response examples
- Specify required parameters
- List possible error responses
- Keep documentation updated

## Testing APIs

- Test all endpoints thoroughly
- Verify authentication and authorization
- Test error scenarios
- Check response formats
- Validate status codes

## Performance Optimization

- Implement response caching
- Use ETags for conditional requests
- Support compression
- Optimize database queries
- Monitor response times

## Webhooks

- Design webhook payloads carefully
- Include event types
- Implement retry logic
- Sign webhook requests
- Document webhook events

## CORS Configuration

- Configure CORS appropriately
- Limit allowed origins
- Specify allowed methods
- Handle preflight requests
- Document CORS policy

## API Security

- Always use HTTPS
- Validate all input
- Implement request signing
- Audit API usage
- Monitor for abuse

## Backward Compatibility

- Never remove fields
- Add new fields as optional
- Deprecate features gracefully
- Maintain old versions
- Communicate changes clearly

## API Monitoring

- Track response times
- Monitor error rates
- Log API usage patterns
- Alert on anomalies
- Review metrics regularly

## Client Libraries

- Provide SDKs when possible
- Include code examples
- Test client libraries
- Version SDKs with API
- Support multiple languages

## GraphQL Considerations

- Use GraphQL for complex queries
- Implement proper authorization
- Handle N+1 queries
- Rate limit by complexity
- Document schema thoroughly

## API Gateway Patterns

- Consider API gateway for microservices
- Implement request routing
- Handle authentication centrally
- Add request/response transformation
- Monitor gateway performance

## Development Workflow

- Use API-first design
- Mock endpoints early
- Test with real clients
- Version control API specs
- Review API changes carefully

## Common Patterns

- Resource-based URLs
- Nested resources sparingly
- Bulk operations support
- Async processing for long operations
- Webhook notifications

## Anti-Patterns to Avoid

- Exposing database structure
- Inconsistent naming
- Breaking changes without versioning
- Poor error messages
- Missing documentation

## API Standards

- Follow JSON:API or similar spec
- Use ISO 8601 for dates
- Implement UUID for identifiers
- Support internationalization
- Handle timezones properly

## Best Practices Summary

- Version from the start
- Document thoroughly
- Keep responses consistent
- Monitor everything
- Design for developers

Remember: APIs are forever. Design them carefully, version them properly, and never break backward compatibility.
