Skip to main content

API Response

The RAD bundle uses a simple API structure, that basically looks like this:

// it's either success:

interface Success
{
ok: true;
data: any;
}

// or failure:

interface Failure
{
ok: false;
data?: any;
error: string;
}

In data you would then put all your payload data.

In an error case, an error message is provided. You should use error keys here (like form-invalid) instead of full messages, so that your frontend can better react to the error and translate the messages.

Controller Integration​

The bundle has an automatic integration for controllers.

Your controller can just return an ApiResponse and it will be automatically transformed to the proper response.

class MyController
{
public function myAction () : ApiResponse
{
// ...

return new ApiResponse(200, [
"some" => "data",
]);
}
}

The first parameter is the HTTP status code the response should have.

Best Practice

Always use the semantically correct HTTP status codes.

Returning an error can look like this:

return (new ApiResponse(422, [
"formErrors" => ...,
]))
->withError("invalid-request", "user readable error message");

An error response can also return data, like proper error messages, form errors, etc

tip

The ok parameter will be automatically determined by whether the status code is a 2xx success code.

Methods​

withError()​

Sets the machine-readable error key (error) and an optional user-readable message (errorMessage).

return (new ApiResponse(422, [
"formErrors" => $this->normalizeFormErrors($form),
]))
->withError("invalid-form", "Please check the form fields.");

isOk()​

Returns whether the response status code is in the 2xx range.

$response = new ApiResponse(204);
$isSuccess = $response->isOk(); // true

error()​

Static shortcut to create an error response with an error key and optional status code.

return ApiResponse::error("not-found", 404);