mohamed-yasser2725's avatar

Seeking Feedback: Using Custom Response Class for Standardized Responses

Hello everyone,

I've been exploring ways to standardize my API responses in my Laravel application, and I've come across the idea of creating a custom response class, similar to Laravel's JsonResponse, to adhere to the JSend standard.

I've developed a class named JSendResponse which encapsulates the logic for constructing JSend-compliant responses. Here's a brief overview of how it works:

<?php

namespace App\Http\Responses;

use Illuminate\Contracts\Support\Responsable;

class JSendResponse implements Responsable
{
    protected $status;
    protected $data;
    protected $message;

    public function __construct($status, $data = null, $message = null)
    {
        $this->status = $status;
        $this->data = $data;
        $this->message = $message;
    }

    public function toResponse($request)
    {
        $response = [
            'status' => $this->status
        ];

        if (!is_null($this->data)) {
            $response['data'] = $this->data;
        }

        if (!is_null($this->message)) {
            $response['message'] = $this->message;
        }

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

I plan to use this class throughout my application to ensure consistent and well-structured API responses.

Before I proceed further, I would like to gather feedback from the community:

  1. Do you think this approach of creating a custom response class is a good practice?
  2. Are there any potential drawbacks or pitfalls I should be aware of?
  3. Are there alternative approaches or best practices for achieving standardized API responses in Laravel?
0 likes
4 replies
mohamed-yasser2725's avatar

i am not very proficient with laravel so any modifications to my code are welcome, as i haven't tested it yet

martinbean's avatar

@mohamed-yasser2725 The entire point of Eloquent API resource classes is to standardise responses.

Although I personally wouldn’t pick “jsend” as a specification. Putting “success” in the response body is completely redundant; you use the HTTP response status code to determine whether a request was “successful” or not.

1 like
mohamed-yasser2725's avatar

@martinbean i didn't know about API resource classes, i will check out, but i have one more question, wouldn't checking using the status code require extra logic on the frontend? like checking if it's 2xx or 3xx?

mohamed-yasser2725's avatar

@martinbean and i have one more question what if i want to handle errors response how would i do that with api resource classes? is there a similar way to standardize it?

Please or to participate in this conversation.