Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel ApiException returning HTML response and not JSON

I'm trying to figure out why my ApiException is still returning a text/html response instead of a json response as denoted in ApiException render method. It is giving me the correct error message however its not rendering it as json.

/**
 * Get the checklist (depending on type - send from Vue model)
 */
public function fetchChecklist(Request $request)
{
    $id = $request->input('projectId');
    $type = $request->input('type');

    if (empty($id)) {
        throw new ApiException('Project was not provided.');
    }

    if (! $project = RoofingProject::find($id)) {
        throw new ApiException('Project not found.');
    }

    if (empty($type)) {
        throw new ApiException('No checklist type was provided.');
    }

    switch ($request->input('type')) {
        case 'permitting':
            $items = $project->permittingChecklist;
            break;

        case 'permit':
            $items = $project->permitReqChecklist;
            break;

        default:
            throw new ApiException('Checklist not found.');
            break;
    }

    return [
        'status' => 'success',
        'message' => '',
        'items' => $items
    ];
}

App\Exceptions\ApiException.php

<?php

namespace App\Exceptions;

class ApiException extends \Exception
{
    public function render($request)
    {
        return response()->json(['status' => 'error', 'error' => $this->message]);
    }
}
like image 338
user3732216 Avatar asked Jan 02 '23 14:01

user3732216


1 Answers

In your request to the API you can try to add the following to your head/curl call to specify the datatype:

"Accept: application/json"

The laravel application is looking for if the requests expects json.

like image 60
jeremykenedy Avatar answered Jan 05 '23 15:01

jeremykenedy