Laravel API: 'Force' to Return JSON (even without client headers)

preview_player
Показать описание
One of the typical mistakes of API developers is forgetting to send the "Accept: application/json" header. No worries, we can solve it from the Laravel side.

- - - - -
Support the channel by checking out my products:

- - - - -
Other places to follow:
Рекомендации по теме
Комментарии
Автор

A very useful video. This should be in Laravel by default.

roman_zabigaliuk
Автор

I like this, it helps ensure a smooth experience and always receiving json back.

Though in the other hand I think the developer should ensure that correct headers are set.

I use an different middleware that checks for the header in this video and return a json response that the Accept header is missing and that it should be set to application/json

Chim
Автор

It is important that AlwaysAcceptJson should be before the throttle:api if you want that 429 response and model not found response (when use model binding in controller) also returned json

ercog
Автор

Awesome awesome awesome, react native developers always annoying me for this

shubhamsahuSD
Автор

Personnaly, I don't know whether is a good practice or not, but I have try-catch blocs everywhere for every command/request. So if I catch somthing, there is always a log ($exception->getMessage() ) for dev and a return JsonResponse with custom message and $expection->getCode() for client.

The thing I note is that I always forget to catch Error, just Exception, and then maybe I could use that middleware trick

jacquesmatike
Автор

Nice one @Povilas, What if we need to send a binary file in one of the api routes if we apply middleware globally??

harikrishna
Автор

Is there any way to do this for a filament project? https

orlandoberssane
Автор

nice trick but still the error is the stack trace no? how looks in production? i personally would go with an error handler that return a proper error

andresgutgon
Автор

Thats a nice video. Can you make a Video how to set Custom Error Messages for a JSON API?

luckyplayax
Автор

how to send real-time notification to flutter with laravel as backend.?

e.g. tell delivery by new orders.

محمدابراهيم-ظض