I have some doubts about validating parameters coming from a route. This is an example code, but I’m not sure if it’s 100% correct as a best practice.
Regarding the various ids that are passed on the route, is it good practice to check that the id actually exists in the table? If so, should the message returned as an API response still be generic, or is it okay to specify that "nothing was found for parameter x"? However, this exposes which ids exist in the table to external people.
public function show(int $firstParam, int $secondParam, int $thirdParam): JsonResponse
{
$rulesForId = ['required', 'numeric'];
Validator::validate(
[ 'firstParam' => $firstParam, 'secondParam' => $secondParam, 'thirdParam' => $thirdParam ],
[ 'firstParam' => $rulesForId, 'secondParam' => $rulesForId, 'thirdParam' => $rulesForId]
);
try {
// Business logic
} catch (ModelNotFoundException $e) {
// Return error response
return Response::error($e->getMessage(), HttpResponse::HTTP_NOT_FOUND);
}
}
>Solution :
It all depends on what you are trying to achieve.
There’s nothing wrong if you return 404 and let client know that the item with this ID does not exist, but again it depends.
Lets say you have bank app. If you have user A
with a wallet (lets give it ID of 1). Then user B
tries to GET /api/wallet/1
(this wallet belongs to user A
) instead of returning 403(not allowed) you can still return 404, as for user B
wallet with id 1 does not exist (also you dont let user B
know that such wallet exists).
If you dont want anybody to know how much records you have in table(or to know approximate number) you can use UUID to your table.
Then request(example) might look like GET /api/wallet/66830110-adf4-11ed-afa1-0242ac120002
. Nobody from the outside can find out how much records you have.
I think what you need is – first find the item with such id (if not found then 404), then check if client who requests this resource has permissions to read/write it. if one does not, then you can still return 404 as for this client requested resource does not exist.
Also be careful when you typehint input parameter with int
as all incoming data is usually a string, this code might fail if one of your parameters wont be a number.