When making a POST, PUT, PATCH request with badly formed body (e.g. wrong types, missing required fields) to an unknown endpoint, should that return 404 or 400?
Example:
- There exists an endpoint
/resource/:resourceId
. - There exists a resource with
resourcedId: 1
. - Endpoint requires
2
fields forPUT
request.enable: boolean
andcount: number
. - Client makes the following request
PUT /resource/2
with body{ enable: 7 }
.
Should the server return 404 (because resource with resourceId: 2
does not exist) or 400 (because body is in invalid format)?
CodePudding user response:
The first check you should make is whether the request launched by your client is well formed.
If it's not well-formed, you should return a 400 Bad Request Error
, preventing it from going beyond your controller.
In case the request is well formed, you allow it to access your business logic layer and if it does not find the resource it is looking for (in your case the '2') then you must return a 404 Not Found Error
.
In case of doubt, you have a lot of documentation about HTTP codes
, I leave you for example this documentation from wikipedia