Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

panthro's avatar

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?

0 likes
3 replies
SilenceBringer's avatar

@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

1 like
panthro's avatar

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?

martinbean's avatar

@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.

1 like

Please or to participate in this conversation.