Skip to main content

Responses

Introduction​

Controllers return data; the router serializes it. Response builds the envelope both transports share:

use YourPlugin\Deps\BitApps\WPKit\Http\Response;

return Response::success($tag);
return Response::error('Tag not found');

The envelope​

Every response is JSON with the same shape:

{
"status": "success",
"code": "SUCCESS",
"message": "Tag saved",
"data": { "id": 12, "title": "Leads" }
}

status is always success or error. message and code appear only when set. data carries the payload.

Success and error​

Response::success($data); // status success, HTTP 200
Response::success($data, 201); // custom HTTP status

Response::error('Failed to save tag'); // status error, HTTP 400
Response::error($errors, 422);

Both take a string or any serializable value as the payload, and both return the instance so you can keep chaining.

Shaping the envelope​

return Response::success($flow)
->message('Flow saved')
->code('FLOW_SAVED')
->httpStatus(201)
->headers(['X-Flow-Id' => $flow->id]);
MethodSets
message($message)Human-readable message field
code($code)Machine-readable code field for the client to branch on
httpStatus($code)HTTP status. Defaults to 200 for success, 400 for error
headers($headers)Response headers, as a name => value array

Read the current values back with getData(), getStatus(), getMessage(), getCode(), getHttpStatusCode() and getHeaders().

Returning bare values​

A controller may return anything. Values that are not a Response are wrapped automatically:

public function index()
{
return Tag::get(['id', 'title', 'status']);
}

becomes

{ "status": "success", "code": "SUCCESS", "data": [ ... ] }

A WP_Error is unwrapped into an error response, mapping its code, message and data:

return new WP_Error('invalid_flow', 'Flow not found', ['id' => $id]);
{ "status": "error", "code": "invalid_flow", "message": "Flow not found", "data": { "id": 42 } }

Transport differences​

The same envelope is delivered two ways:

TransportDelivery
AJAXHeaders are sent, then wp_send_json() with the HTTP status
RESTA WP_REST_Response carrying the data, status and headers
note

Anything a controller echoes or prints before returning is captured and attached to the envelope as an additional field, rather than corrupting the JSON. Treat it as a debugging aid: stray output means a stray var_dump().

warning

Response stores its state in static properties, so one request builds one response. Do not build two responses side by side and expect them to stay independent — the second overwrites the first.