Skip to content

Error Models

ErrorResponse

ErrorResponse(error: str, details: Optional[List[Dict[str, Any]]] = None, request_id: Optional[str] = None, trace_id: Optional[str] = None)

Fallback ErrorResponse when Pydantic is not available.

Functions

model_dump_json

model_dump_json(**kwargs)

Serialize to JSON string.

model_dump

model_dump(**kwargs)

Serialize to dict.

from_validation_error classmethod

from_validation_error(error: Any, message: str = 'Validation failed', request_id: Optional[str] = None, trace_id: Optional[str] = None)

Create an ErrorResponse from a validation error.

ValidationError module-attribute

ValidationError = ValidationError

Overview

Error models provide structured error responses for REST APIs.

ErrorResponse

Standard error response format:

from restmachine import ErrorResponse

@app.get('/users/{user_id}')
def get_user(user_id: str):
    user = db.get(user_id)

    if not user:
        return ErrorResponse(
            error="Not Found",
            message=f"User {user_id} not found",
            status_code=404
        )

    return user

ValidationError

Raised when request validation fails:

from pydantic import BaseModel
from restmachine import ValidationError

class UserCreate(BaseModel):
    name: str
    email: str

@app.post('/users')
def create_user(request):
    try:
        data = UserCreate.model_validate_json(request.body)
    except Exception as e:
        raise ValidationError(str(e))

    return {"created": data.model_dump()}, 201

See Also