Spaces:
Running
Running
File size: 7,622 Bytes
3dea2cf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | # API Development Standards
## List Endpoint Requirements
**MANDATORY**: All list/fetch endpoints MUST implement projection list support.
### Standard Pattern
#### 1. Request Schema
Every list request schema must include:
```python
from typing import Optional, List
from pydantic import BaseModel, Field
class ResourceListRequest(BaseModel):
"""Schema for listing resources with filters."""
# Your filters here
skip: int = Field(0, ge=0, description="Number of records to skip (pagination)")
limit: int = Field(100, ge=1, le=500, description="Maximum number of records to return")
# MANDATORY: Projection list field
projection_list: Optional[List[str]] = Field(
None,
description="List of fields to include in response (e.g., ['id', 'name', 'status'])"
)
class Config:
json_schema_extra = {
"example": {
"skip": 0,
"limit": 100,
"projection_list": ["id", "name", "status", "created_at"]
}
}
```
#### 2. Service Layer
Services must support MongoDB projection:
```python
from typing import Optional, List, Dict, Any
async def list_resources(
filters: Dict[str, Any],
skip: int = 0,
limit: int = 100,
projection_list: Optional[List[str]] = None
):
"""List resources with optional field projection."""
# Build query
query = {}
# ... add your filters
# MANDATORY: Build projection dict
projection_dict = None
if projection_list:
projection_dict = {field: 1 for field in projection_list}
projection_dict["_id"] = 0 # Always exclude MongoDB _id
# Query with projection
cursor = collection.find(query, projection_dict).skip(skip).limit(limit)
documents = await cursor.to_list(length=limit)
# MANDATORY: Return raw dict if projection, model otherwise
if projection_list:
return documents # List[Dict]
else:
return [ResponseModel(**doc) for doc in documents] # List[ResponseModel]
```
#### 3. Controller Layer
Controllers must pass projection to service:
```python
@router.post("/list", summary="List resources")
async def list_resources(payload: ResourceListRequest):
"""
List resources with optional filters and field projection.
**Request Body:**
- `skip`: Pagination offset (default: 0)
- `limit`: Page size (default: 100, max: 500)
- `projection_list`: Optional list of fields to include in response
"""
result = await ResourceService.list_resources(
filters=payload.filters,
skip=payload.skip,
limit=payload.limit,
projection_list=payload.projection_list # MANDATORY: Pass projection
)
# Return result (service handles projection logic)
return result
```
### Endpoint Specifications
#### HTTP Method
- **REQUIRED**: Use `POST` method for all list endpoints
- **Reason**: POST allows complex request bodies with filters and projection
#### Endpoint Path
- **Pattern**: `POST /{resource}/list`
- **Examples**:
- `POST /employees/list`
- `POST /merchants/list`
- `POST /sales/order/list`
#### Response Format
- **With projection**: Returns `List[Dict[str, Any]]` (raw dictionaries)
- **Without projection**: Returns `List[ResponseModel]` (typed Pydantic models)
### Implementation Checklist
When creating a new list endpoint, ensure:
- [ ] Request schema includes `projection_list: Optional[List[str]]` field
- [ ] Service method accepts `projection_list` parameter
- [ ] Service builds MongoDB projection dict when `projection_list` is provided
- [ ] Service returns raw dicts for projection, models otherwise
- [ ] Controller passes `projection_list` to service
- [ ] Endpoint uses POST method
- [ ] Endpoint path follows `/{resource}/list` pattern
- [ ] Documentation includes projection examples
- [ ] Tests cover both projection and non-projection scenarios
### Example Request/Response
#### Request with Projection
```json
POST /employees/list
{
"designation": "ASM",
"status": "active",
"skip": 0,
"limit": 10,
"projection_list": ["user_id", "first_name", "last_name", "email"]
}
```
#### Response with Projection
```json
[
{
"user_id": "usr_123",
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com"
},
{
"user_id": "usr_456",
"first_name": "Jane",
"last_name": "Smith",
"email": "jane.smith@example.com"
}
]
```
#### Request without Projection
```json
POST /employees/list
{
"designation": "ASM",
"status": "active",
"skip": 0,
"limit": 10
}
```
#### Response without Projection
```json
[
{
"user_id": "usr_123",
"employee_code": "EMP001",
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com",
"phone": "+919876543210",
"designation": "ASM",
"status": "active",
"manager_id": "usr_789",
"region": "North",
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-20T14:45:00Z"
// ... all other fields
}
]
```
### Benefits
1. **Performance**: Reduces database I/O and network bandwidth
2. **Flexibility**: Clients request only what they need
3. **Consistency**: Uniform pattern across all list endpoints
4. **Scalability**: Better performance for mobile and low-bandwidth clients
### Common Use Cases
#### Dashboard Widgets
```json
{
"projection_list": ["id", "name", "status", "count"]
}
```
#### List Views
```json
{
"projection_list": ["id", "name", "created_at", "status"]
}
```
#### Dropdown/Select Options
```json
{
"projection_list": ["id", "name"]
}
```
#### Export Operations
```json
{
"projection_list": ["id", "name", "email", "phone", "status", "created_at"]
}
```
### Anti-Patterns (DO NOT DO)
❌ **Don't use GET with query parameters for complex filters**
```python
# BAD
@router.get("/list")
async def list_resources(
filter1: str = None,
filter2: str = None,
# ... many parameters
):
```
❌ **Don't ignore projection in service layer**
```python
# BAD
async def list_resources(projection_list: Optional[List[str]] = None):
# Ignoring projection_list parameter
cursor = collection.find(query) # Missing projection
return [Model(**doc) for doc in documents] # Always returning models
```
❌ **Don't return inconsistent response types**
```python
# BAD - Always return same type regardless of projection
if projection_list:
return [Model(**doc) for doc in documents] # Should return raw dicts
```
### Migration Guide
For existing GET endpoints without projection:
1. Create new POST endpoint with projection support
2. Keep GET endpoint for backward compatibility (if needed)
3. Update documentation to recommend POST endpoint
4. Deprecate GET endpoint in next major version
5. Remove GET endpoint after deprecation period
### Testing Requirements
Every list endpoint must have tests for:
1. **Full response** (no projection)
2. **Partial projection** (subset of fields)
3. **Single field projection**
4. **Invalid field projection** (non-existent fields)
5. **Empty projection list** (should return full response)
6. **Pagination with projection**
7. **Filters with projection**
### Documentation Requirements
API documentation must include:
1. Request schema with projection_list field
2. Example requests with and without projection
3. Example responses for both scenarios
4. List of commonly used field combinations
5. Performance recommendations
---
**Last Updated**: December 2024
**Applies To**: All microservices (SCM, POS, Auth, etc.)
**Status**: MANDATORY for all new list endpoints
|