E
E
Eternal972021-02-26 13:13:23
RESTful API
Eternal97, 2021-02-26 13:13:23

How to correctly return a response from controller methods using the REST API methodology?

Good day. After reading many articles on REST Api on Laravel, confusion appeared in my head. Please help clarify one question. Let's say I have a User entity and I want to get, delete or update the entity in the database using the update and destroy methods in the controller. All articles say that the controller method returns a response in JSON format. Example:

public function index()
    {
        $users = User::all();
        return response()->json($users, 200);
    }

public function update(UserRequest $request, $id)
     {
         $user = User::findOrFail($id);
         $user->fill($request->except(['user_id']));
         $user->save();
         return response()->json($user);
     }

public function destroy(UserRequest $request, $id)
     {
         $user = User::findOrFail($id);
         if($user->delete()) return response(null, 204);
     }

The question is, is it mandatory to give JSON and server responses 200, 204, 404, and if so, how to pass JSON to the view, or can I do it like this:
public function index()
    {
        $users = User::all();
        return view('userlist', compact('users')):
    }

public function update(UserRequest $request, $id)
     {
         $user = User::findOrFail($id);
         $user->fill($request->except(['user_id']));
         $user->save();
         return redirect()->route('userlist');
     }

public function destroy(UserRequest $request, $id)
     {
         $user = User::findOrFail($id);
         return redirect()->route('userlist');
     }

And if I do this, will it be considered a REST Api?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-02-26
@Eternal97

is it necessary to send JSON and server responses 200, 204, 404
The REST police won't arrest you, of course. But these are generally accepted conventions. Because...
would this be considered a REST Api
...most probably not. Because you will be giving back the data mixed in with the view. And so that, having received a list of entities, the front-end could request detailed information on one of them, it will first need to pick out its identifier from the layout.
REST allows the server to be responsible only for the data, and some other program is responsible for the presentation of this data. And therefore, the data is given in a form convenient for work and with understandable response codes, so that the client application can execute some logic based on this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question