Alpesh Maniya
What status code should an API return when providing a validation message?
By Alpesh Maniya in .NET on Jan 05 2024
  • Jayraj Chhaya
    Jan, 2024 12

    Returning a 422 status code along with a detailed validation message in the response body allows the client to understand the reason for the failure and take appropriate action. The response body can include information about the specific validation errors, such as missing or invalid input, format requirements, or any other relevant details.

    1. [HttpPost]
    2. public IActionResult Create([FromBody] MyModel model)
    3. {
    4. if (!ModelState.IsValid)
    5. {
    6. var validationErrors = ModelState.Values
    7. .SelectMany(v => v.Errors)
    8. .Select(e => e.ErrorMessage)
    9. .ToList();
    10. return StatusCode(422, new { errors = validationErrors });
    11. }
    12. // Process the valid request
    13. // ...
    14. return Ok();
    15. }

    • 0
  • SACHIN DALAL
    Jan, 2024 12

    422

    • 0
  • Rameez Hasan
    Jan, 2024 11

    When an API encounters a validation error, it should typically return a 422 Unprocessable Entity status code. The HTTP 422 status code indicates that the server understands the content type of the request but was unable to process the contained instructions.In the context of validation errors, a 422 status code communicates that the server received the request, but the data within the request did not pass validation. Alongside the 422 status code, the API should provide details about the validation errors in the response body, typically in a well-structured format (e.g., JSON). This allows the client to understand which parts of the request failed validation and provides specific error messages or guidance for correction.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS