Reputation: 885
I have users into my app with two different roles, Student and Admin. Each user has a team_id field reference which tells the user which team it belongs. In this case my db consists of these tables : users,teams.
And to show a team details I have an API like below: GET: api/teams/{team_id}
public function show($id)
{
$team = $this->teamService->findById($id);
if ($team) {
return response()->json(['message' => 'Success', 'success' => true, 'status' => 200, 'data' => $team]);
} else {
return response()->json(['message' => 'Error', 'success' => true, 'status' => 404, 'data' => null]);
}
}
Well this is for admin only as the $id is passed as an argument into the url, that means only admin can put any $id, while the normal user the id has to be automatically associated depending what team they belong(so in this case I want to show the team details for the team they belong).
so in this case my api should look like this: GET: api/teams
public function show()
{
$team = $this->teamService->findById(Auth->user->team_id); //associate the team id for user logged in
if ($team) {
return response()->json(['message' => 'Success', 'success' => true, 'status' => 200, 'data' => $team]);
} else {
return response()->json(['message' => 'Error', 'success' => true, 'status' => 404, 'data' => null]);
}
}
So my final question is, is there any way that I can put this in one place for both roles.. so there will not be duplicate functions for different roles.
What should the API be look like in this case?
Thanks
Upvotes: 0
Views: 808
Reputation: 13065
Do I need to write seperate APIs endpoint for each user role?
No, definitely not.
What should the API be look like in this case?
There is no "right" answer, but here are two ideas:
1) The User object should have links to your team object:
{ name: "bob", team_link: "/team/3" }
Then your /team/:id
route should check "If you are not the admin user, give a 404 if user is not on this team."
2) If you really think a user needs to get their team info as it's own call, you can have a /team
route. But the above is more standard. Or, serve a link to the real team object. (Why? Because it makes caching easier down the road.)
Upvotes: 1