In the current scenario, for the POST request on /books, if there is a missing required field, it throws an error.
POST http://localhost:8080/books
Content-Type: application/json
{
"description": "Timeless lessons on wealth, greed, and happiness doing well with money",
"author": "Morgan Housel"
}
This request doesn't contain the name required field, so it cannot create a [Book] object in the following code, causing the route handler to fail.
final book = Book.fromJson(
await context.request.json() as Map<String, dynamic>,
);
Solution
Check if the field is available in the request body, and if the value is of type [String]. The solution might become cumbersome for multiple fields and complex validation logic.
final reqBodyJson = await context.request.json() as Map<String, dynamic>;
if (!reqBodyJson.containsKey('name') && reqBodyJson['name'] is! String) {
return Response.json(
statusCode: HttpStatus.badRequest,
body: 'The `name` field is missing in the request body',
);
}
Description
In the current scenario, for the POST request on
/books
, if there is a missing required field, it throws an error.This request doesn't contain the
name
required field, so it cannot create a [Book] object in the following code, causing the route handler to fail.Solution
Check if the field is available in the request body, and if the value is of type [String]. The solution might become cumbersome for multiple fields and complex validation logic.