JSON Post Request Payload Validation? #2272
-
|
In a post request, there is a payload that should be validated with the following schema, struct CreateAccountSchema {
std::string Name;
std::string PlatformId;
};I try to validate it with the following snippet I got from the docs. Router.post("/accounts", [Database](const glz::request &Request, glz::response &Response) {
CreateAccountSchema AccountData;
if (auto JsonError = glz::read_json(AccountData, Request.body)) {
Response.status(static_cast<int>(BadRequest))
.json({{"error", "Invalid JSON"}});
return;
}But the following payload still went through, {
"Name": "guzman109",
}Any advice on how I can enforce all fields are correct? Luckily I handled it before it got committed to the database but I would like to see that it was an invalid payload. I come from writing backends in FastAPI and validating with Pydantic. My thought was that glaze would be similar, then again I'm most likely using it incorrectly. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
By default, To enforce that all fields are present, use CreateAccountSchema AccountData;
constexpr my_opts = glz::opts{.error_on_missing_keys = true};
if (auto JsonError = glz::read<my_opts>(AccountData, Request.body)) {
Response.status(static_cast<int>(BadRequest))
.json({{"error", "Invalid JSON"}});
return;
}This will return A few additional notes:
template <>
struct glz::meta<CreateAccountSchema> {
static constexpr bool requires_key(std::string_view key, bool is_nullable) {
// Custom logic per field
return !is_nullable;
}
};See docs/field-validation.md and docs/options.md for more details. |
Beta Was this translation helpful? Give feedback.
By default,
glz::read_jsondoes not error on missing keys — any fields absent from the JSON are left at their default-constructed values. This is why your payload with only"Name"passes without error.To enforce that all fields are present, use
glz::readwith theerror_on_missing_keysoption:This will return
glz::error_code::missing_keyif any non-nullable field is missing from the input JSON.A few additional notes: