0

Im testing my laravel rest API with postman, my end point only allow POST method but when i test it with GET method the body return webpage instead of json. How could i handle the response to return json although the response is 405? enter image description here

Ferry Sanjaya
  • 224
  • 2
  • 17

1 Answers1

4

You can handle it in function render of app/Exceptions/Handler.php

Ex:

public function render($request, Exception $e)
{
   if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
      return response()->json(['message' => $e->getMessage(), 405);
   }
   return parent::render($request, $e);
}

The docs for it: https://laravel.com/docs/5.8/errors#render-method

I think Laravel has the response as JSON for it by default. You also can add to headers of request.

Content-Type: application/json
Accept: application/json
Sang Nguyen
  • 1,702
  • 15
  • 16