Skip to content

Responses formatting problem #733

Closed
Closed
@lazar89nis

Description

@lazar89nis

Hey, great package. I was using swagger but wanted something that will auto document my API so I am sure its up to date when I make changes.
I have 2 problems right now.
Problem 1:
I have a custom ApiResponse class like this:

class ApiResponse
{
    public static function success($data = null, $status = 200)
    {
        return response()->json(
            $data,
            $status
        );
    }

    public static function error($message = 'An error occurred.', $code = 'BAD_REQUEST', $status = 400, $errors = [])
    {
        return response()->json(data: [
            'success' => false,
            'code' => $code,
            'message' => $message,
            'errors' => $errors,
        ], status: $status);
    }
}

And when i am returning data i have code like this:

return ApiResponse::success(
            new TokenResource($token)
        );
class TokenResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'access_token' => $this->resource,
            'token_type' => 'Bearer',
        ];
    }
}

In the documentation i get
{
"data": {
"access_token": "string",
"token_type": "Bearer"
}
}
It should not add 'data'.

On the other hand when I have it like this:

return ApiResponse::success(
            ['email_exists' => $emailExists]
        );

I get it without data
{
"email_exists": "string"
}

Is there any way to fix this?

Problem 2, all my Requests extends BaseFormRequest and it has failedValidation function but its not registered by scramble.

class BaseFormRequest extends FormRequest
{
    protected function failedValidation(Validator $validator)
    {
        $response = response()->json([
            'success' => false,
            'code' => ErrorCode::VALIDATION_ERROR,
            'message' => 'The given data was invalid.',
            'errors' => $validator->errors(),
        ], 422);

        throw new ValidationException($validator, $response);
    }
}
class SocialRegisterRequest extends BaseFormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules()
    {
        return [
            'provider' => ['required', 'string', 'in:facebook,google,apple'],
            'social_id' => ['required', 'string'],
            'email' => ['required', 'string'],
            'user_name' => 'required|string|min:4|max:40',
        ];
    }
}

I am getting 422
{
"message": "string",
"errors": {
"property1": [
"string"
],
"property2": [
"string"
]
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions