weno
weno

Reputation: 856

Passing invalid ID to an endpoint: how to handle such a case?

Consider /v1/api/people/{id} endpoint handling GET, PUT and DELETE operations, where id is an integer.

I am wondering about how the below two cases should typically be handled?

a). when passed id does not exists in database, e.g. id = 100 but there is no entity of such id

b). when passed id is of wrong type e.g. it is a string "oops"

Imagine that both of above errors never actually happen as far as the real application is concerned (because e.g. application has "correct" workflow and some client-side validation).

However, I can still cause the above errors in let's say Postman or if something changes in the future, right? I want to prevent those errors in the future.

Should it be left as HTTP 500 or perhaps should it be handled as HTTP 400 or HTTP 404? Is HTTP 500 ever acceptable?

Upvotes: 0

Views: 567

Answers (1)

Rahul Sawant
Rahul Sawant

Reputation: 1264

HTTP 500 - should be used as Internal Server Error meaning something unexpected happened in server side .. above errors should be part of validation ideally since they are known scenarios

a). when passed id does not exists in database, e.g. id = 100 but there is no entity of such id

  • here you should return 404(Not Found) with error msg like 'resource with id 100 not present for deletion/update etc' to make it user friendly

b). when passed id is of wrong type e.g. it is a string "oops"

  • here you should show 400 (BadRequest) since user is not passing value as per agreement that is resource id.

Upvotes: 3

Related Questions