Search code examples
laravelrestaxioslaravel-api

Laravel API Response Object formatting


I have created a basic Laravel REST API that will service some JavaScript applications that are using axios to make requests.

My application is using a Base Controller to ensure all responses are sent in the same format:

class BaseController extends Controller
{
    /**
     * success response method.
     *
     * @param $result
     * @param $message
     *
     * @return JsonResponse
     */
    public function sendResponse($result, $message)
    {
        $response = [
            'success' => true,
            'data' => $result,
            'message' => $message,
        ];

        return response()->json($response, 200);
    }

    /**
     * return error response.
     *
     * @param $error
     * @param  array  $errorMessages
     * @param  int  $code
     *
     * @return JsonResponse
     */
    public function sendError($error, $errorMessages = [], $code = 200)
    {
        $response = [
            'success' => false,
            'message' => $error,
        ];

        if (!empty($errorMessages)) {
            $response['data'] = $errorMessages;
        }

        return response()->json($response, $code);
    }
}

When I retrieve the response from the API URL and log it to the console, I get the following output:

enter image description here

Currently, my response object contains its own data object, which then contains another data object. As a result, to access the data I have to use response.data.data.

I am wondering if this is actually the correct way to do this. As the naming convention of response.data.data doesn't seem to be a very clean way to do this. I have seen a couple of guides online where it has been done this way, but I am wondering if there are any typically followed conventions that I am missing. Perhaps this is correct but I just wanted some insight from more experienced programmers.


Solution

  • In my opinion how you are approaching it is fine:

    • response is the full response object via axios
    • response.data is the full response body that was returned
    • response.data.data is the data node of the response body that was returned

    Some suggestions:

    • instead of using success in your response, that can be implied from the returned status code: anything within 200-299 is successful, anything 300-399 is a redirect, anything 400-499 is a client error, and anything 500+ is a server error (see here)
    • instead of using data in the instance of an error, in my opinion that node should be reserved for successful data and a node such as errors should be used instead
    • your sendError method should default to a status code of 500 instead of 200, as 200 is a successful status code