What status code should an API return when providing a validation message?
Alpesh Maniya
Select an image from your device to upload
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.
[HttpPost]public IActionResult Create([FromBody] MyModel model){ if (!ModelState.IsValid) { var validationErrors = ModelState.Values .SelectMany(v => v.Errors) .Select(e => e.ErrorMessage) .ToList(); return StatusCode(422, new { errors = validationErrors }); } // Process the valid request // ... return Ok();}
[HttpPost]
public IActionResult Create([FromBody] MyModel model)
{
if (!ModelState.IsValid)
var validationErrors = ModelState.Values
.SelectMany(v => v.Errors)
.Select(e => e.ErrorMessage)
.ToList();
return StatusCode(422, new { errors = validationErrors });
}
// Process the valid request
// ...
return Ok();