Response format for API? I'm building a simple API in Laravel.
Is there a standard way or format that responses should be returned in?
Also, if there is an error should I throw an exception or pass back a json response with an error like 500/404 etc.
What's the standard practice - can someone point me in the right direction?
@panthro look at https://laravel.com/docs/8.x/eloquent-resources - the best way to format your output
Also, if there is an error should I throw an exception or pass back a json response with an error like 500/404 etc.
End your should not receive throwed exception. You need to catch exceptions and send appropriate json response with correct message and status code
Thank you - I will review that link.
But what happens when I am not returning a resource like an eloquent collection?
For example, on login:
if (!Auth::attempt($request->validated())) {
// return an error
} else {
$request->session()->regenerate();
// return succsess
}
How would you deal with the above?
@panthro You should just return representations of your models. For errors, return a consistent format. Clients shouldn’t have to write a load of conditional logic to handle different types of errors.
If you throw appropriate exceptions, Laravel will convert it to an appropriate HTTP response automatically.
Please sign in or create an account to participate in this conversation.