请求体错误场景下的HTTP状态码确认:数据类型错误该返回何码?
1. 400 vs. 422 for Invalid Data Types
Let’s break down which status code fits your scenario and why:
400 Bad Request: This is reserved for cases where the server can’t even parse or understand the request due to a syntax error. Examples include:
- Malformed JSON (missing a closing bracket, misplaced comma, unquoted keys)
- Sending the wrong content type entirely (like form data when the API expects JSON)
422 Unprocessable Entity: This is the precise choice when the request is syntactically valid (your JSON is properly formatted and the server can parse it) but semantically invalid. Your example falls directly into this category:
- You’re sending a valid JSON object, but fields like
id(expectedint, gotstring) andactivated(expectedboolean, gotstring) don’t match the required data types. The server understands the request structure, but can’t process it because of these validation failures.
- You’re sending a valid JSON object, but fields like
So for your specific case, returning 422 is the most REST-compliant and clear choice.
2. Questions About the id Field
It looks like your question about the id field was cut off! If you can share more details—like whether the id should be client-provided or auto-generated by the server, validation rules you’re considering, or edge cases you’re worried about—I can help you work through that too.
内容的提问来源于stack exchange,提问作者Michael 12345

