Skip to content

API Response Format Standardization #7

@dev-wantap

Description

@dev-wantap

API Response Format Standardization

Objective

Standardize all API endpoint response formats to ensure consistency and improve maintainability across the application. Currently, endpoints use multiple inconsistent response structures which makes client integration difficult and error-prone.

Current Issues

Inconsistent Response Formats

The codebase currently uses at least 3 different response patterns:

Pattern 1: status + message

{"status": "success", "message": "Server started (fake)"}
{"status": "error", "message": str(e)}

Pattern 2: success + result/error

{"success": True, "result": "..."}
{"success": False, "error": "..."}

Pattern 3: status + custom fields

{"status": "running", "connected": True}
{"status": "running", "player_count": "3"}

Unused Response Model

A CommandResponse model exists in models/responses.py but is not being used by any endpoints:

class CommandResponse(BaseModel):
    status: str
    message: str
    data: Optional[Any] = None  
    timestamp: datetime = datetime.now()

Proposed Solution

Create a unified ApiResponse model and apply it consistently across all endpoints.

Recommended Response Structure

class ApiResponse(BaseModel):
    success: bool
    message: str = ""
    data: Optional[dict] = None

Success Response Example:

{
  "success": true,
  "message": "Command executed successfully",
  "data": {
    "result": "Player kicked",
    "player": "username"
  }
}

Error Response Example:

{
  "success": false,
  "message": "Failed to execute command",
  "data": {
    "error": "Connection timeout"
  }
}

Tasks

Response Model Updates

  • models/responses.py - Create new ApiResponse model or refactor existing CommandResponse
  • models/responses.py - Add typed response models for specific use cases (e.g., PlayerListResponse, ServerStatusResponse)

Router Updates

  • routers/server.py - Update all endpoints to use unified response format

    • /start - Standardize response
    • /stop - Standardize response
    • /restart - Standardize response (also fix infinite recursion bug)
    • /status - Standardize response
    • /test-connection - Standardize response
    • /commands - Standardize response
    • /announce - Standardize response
    • /gamerule - Standardize response
  • routers/players.py - Update all endpoints to use unified response format

    • / (get_players) - Standardize response
    • /player_list - Standardize response
    • /kick - Standardize response
    • /ban - Standardize response
    • /pardon - Standardize response

Documentation

  • Update README.md with response format examples

Additional Fixes

Critical Bug Fix

  • Fix infinite recursion in routers/server.py /restart endpoint
    @router.post("/restart")
    def start_server():  # Wrong function name!
        try:
            stop_server()
            start_server()  # Infinite recursion!

File Structure

parallelstone_manager/
├── models/
│   ├── responses.py           # Unified response models
│   └── players.py
└── routers/
    ├── server.py              # 8 endpoints to update
    └── players.py             # 5 endpoints to update

Success Criteria

  • All API endpoints return responses in consistent format
  • Pydantic models are used for response validation
  • No breaking changes for critical endpoints (or documented migration guide provided)

Benefits

  • Better Type Safety: Pydantic models provide automatic validation
  • Easier Client Integration: Consistent structure simplifies client code
  • Improved Documentation: FastAPI auto-docs will show proper response schemas
  • Maintainability: Single source of truth for response structure
  • Debugging: Standardized error format makes logging and monitoring easier

Follow-up Tasks

  • Add response status codes standardization (200, 400, 404, 500)
  • Implement exception handlers for consistent error responses
  • Add response examples to OpenAPI schema
  • Consider adding response pagination model for list endpoints

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions