Backend

API Design Standards

RESTful API design guidelines for building consistent, intuitive, and developer-friendly APIs.

Cursor Add to Cursor
Cursor Rule (.mdc)

Copy this complete rule and save it as a .mdc file in your .cursor/rules directory

# API Design Standards

## URL Structure

### Resource Naming
- Use nouns, not verbs: `/users` not `/getUsers`
- Use plural forms: `/posts` not `/post`
- Use kebab-case: `/user-profiles` not `/userProfiles`
- Keep URLs lowercase

### Hierarchy
```
GET /users                    # List users
GET /users/123                # Get user 123
GET /users/123/posts          # Get posts by user 123
GET /users/123/posts/456      # Get post 456 by user 123
```

### Query Parameters
- Filtering: `?status=active&role=admin`
- Sorting: `?sort=created_at&order=desc`
- Pagination: `?page=2&limit=20` or `?cursor=abc123`
- Field selection: `?fields=id,name,email`
- Search: `?q=search+term`

## HTTP Methods

| Method | Usage | Idempotent |
|--------|-------|------------|
| GET | Retrieve resources | Yes |
| POST | Create new resources | No |
| PUT | Replace entire resource | Yes |
| PATCH | Partial update | Yes |
| DELETE | Remove resource | Yes |

## Request/Response Format

### Request Headers
```http
Content-Type: application/json
Accept: application/json
Authorization: Bearer <token>
X-Request-ID: uuid
```

### Success Response
```json
{
  "data": {
    "id": "123",
    "type": "user",
    "attributes": {
      "name": "John Doe",
      "email": "[email protected]"
    }
  },
  "meta": {
    "requestId": "req_abc123"
  }
}
```

### Collection Response
```json
{
  "data": [
    { "id": "1", "name": "Item 1" },
    { "id": "2", "name": "Item 2" }
  ],
  "meta": {
    "total": 100,
    "page": 1,
    "limit": 20,
    "hasMore": true
  },
  "links": {
    "self": "/api/items?page=1",
    "next": "/api/items?page=2",
    "prev": null
  }
}
```

### Error Response
```json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request data",
    "details": [
      {
        "field": "email",
        "message": "Must be a valid email address"
      }
    ]
  },
  "meta": {
    "requestId": "req_abc123"
  }
}
```

## HTTP Status Codes

### Success (2xx)
- `200 OK` - Successful GET, PUT, PATCH
- `201 Created` - Successful POST
- `204 No Content` - Successful DELETE

### Client Errors (4xx)
- `400 Bad Request` - Invalid syntax
- `401 Unauthorized` - Missing/invalid authentication
- `403 Forbidden` - Valid auth, insufficient permissions
- `404 Not Found` - Resource doesn't exist
- `409 Conflict` - Resource conflict (duplicate)
- `422 Unprocessable Entity` - Validation errors
- `429 Too Many Requests` - Rate limit exceeded

### Server Errors (5xx)
- `500 Internal Server Error` - Unexpected error
- `502 Bad Gateway` - Upstream service error
- `503 Service Unavailable` - Temporary overload

## Versioning

### URL Versioning (Recommended)
```
/api/v1/users
/api/v2/users
```

### Header Versioning
```http
Accept: application/vnd.api+json; version=2
```

## Authentication

### Bearer Token
```http
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
```

### API Key
```http
X-API-Key: your-api-key
```

## Rate Limiting

### Response Headers
```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
Retry-After: 60
```

## Best Practices

1. **Be Consistent**: Same patterns across all endpoints
2. **Use HTTPS**: Always encrypt in transit
3. **Version Your API**: Plan for backwards compatibility
4. **Document Everything**: OpenAPI/Swagger specs
5. **Validate Input**: Never trust client data
6. **Handle Errors Gracefully**: Meaningful error messages
7. **Implement Rate Limiting**: Protect against abuse
8. **Use Caching Headers**: ETag, Cache-Control
9. **Support CORS**: Enable cross-origin requests appropriately
10. **Log Requests**: For debugging and analytics
Key Capabilities

What this rule helps you achieve

RESTful design patternsConsistent response formatsProper HTTP methodsAPI versioning
Tags
apirestbackendhttp