From 6062b980fc1f4f10c65d1106687389aca69829f1 Mon Sep 17 00:00:00 2001 From: Kevin Chung Date: Fri, 24 Jul 2020 13:43:27 -0400 Subject: [PATCH] Return better errors on invalid API parameters (#1570) * Return better errors on invalid API parameters For example: ``` { "success": false, "errors": { "user_id": "value is not a valid integer" } } ``` --- CTFd/api/v1/helpers/request.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/CTFd/api/v1/helpers/request.py b/CTFd/api/v1/helpers/request.py index 3693f0ba..186d6db0 100644 --- a/CTFd/api/v1/helpers/request.py +++ b/CTFd/api/v1/helpers/request.py @@ -1,7 +1,7 @@ from functools import wraps from flask import request -from pydantic import create_model +from pydantic import ValidationError, create_model ARG_LOCATIONS = { "query": lambda: request.args, @@ -41,7 +41,18 @@ def validate_args(spec, location): @wraps(func) def wrapper(*args, **kwargs): data = ARG_LOCATIONS[location]() - loaded = spec(**data).dict(exclude_unset=True) + try: + # Try to load data according to pydantic spec + loaded = spec(**data).dict(exclude_unset=True) + except ValidationError as e: + # Handle reporting errors when invalid + resp = {} + errors = e.errors() + for err in errors: + loc = err["loc"][0] + msg = err["msg"] + resp[loc] = msg + return {"success": False, "errors": resp}, 400 return func(*args, loaded, **kwargs) return wrapper