Menu

My create endpoint returns 201 and a full user, not a bare id
πŸ“°

My create endpoint returns 201 and a full user, not a bare id

DEV Community: laravelΒ·Kamran KhanΒ·17 days ago
#q8RCJRAN
#devtolaravel#devto#dev#user#return
Reading 0:00
15s threshold

Most create endpoints I see in client codebases return one of two lazy things: a 200 with the new id, or a 200 with a success message and nothing else. Then the frontend has to make a second request to show the thing it just created, or it guesses at the shape and gets it wrong.

In my starter kit, creating a user returns this, every time:

public function store(StoreUserRequest $request): JsonResponse

{

$user = User::create($request->validated());

return response()->json(['user' => new UserResource($user)], 201);

}

Two decisions are packed into those three lines, and both are deliberate.

First, 201, not 200. A 200 says "fine, done." A 201 says "a resource now exists that didn't before." That distinction matters the day you write a frontend that branches on status, or a test that asserts creation actually happened. My register endpoint does the same β€” 201 with the user and a token β€” because registration is also a creation, not a generic success.

Second, the full resource, not a bare id.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.