Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

fix(api): describe the rejected field in validation errors

Rudy Celekli7fb43868f188
diff --git a/app/asgi.py b/app/asgi.py
index c46d552a..0e4f672e 100644
--- a/app/asgi.py
+++ b/app/asgi.py
@@ -74,11 +74,16 @@ def validation_exception_handler(request: Request, e: RequestValidationError):
Exception: str,
},
)
+ # Describe the first rejected field instead of always claiming a missing
+ # field: out-of-range values and malformed JSON are not "field required".
+ message = "invalid request parameters"
+ if errors and isinstance(errors[0], dict):
+ location = ".".join(str(part) for part in errors[0].get("loc") or ())
+ detail = errors[0].get("msg") or message
+ message = f"{location}: {detail}" if location else str(detail)
return JSONResponse(
status_code=400,
- content=utils.get_response(
- status=400, data=errors, message="field required"
- ),
+ content=utils.get_response(status=400, data=errors, message=message),
)
diff --git a/test/services/test_api_validation_message.py b/test/services/test_api_validation_message.py
new file mode 100644
index 00000000..38d921f9
--- /dev/null
+++ b/test/services/test_api_validation_message.py
@@ -0,0 +1,50 @@
+from unittest.mock import patch
+
+import pytest
+from fastapi.testclient import TestClient
+
+from app import asgi
+from app.config import config
+
+
+def _post(path, content):
+ with (
+ patch.dict(config.app, {"api_key": ""}),
+ patch("app.controllers.v1.video.task_manager.add_task") as schedule,
+ patch("app.controllers.v1.llm.llm.generate_script") as generate,
+ TestClient(asgi.get_application(), raise_server_exceptions=False) as client,
+ ):
+ response = client.post(
+ path, content=content, headers={"content-type": "application/json"}
+ )
+ schedule.assert_not_called()
+ generate.assert_not_called()
+ return response
+
+
+ "content, expected",
+ [
+ (
+ '{"video_subject": "sea", "paragraph_number": 0}',
+ "body.paragraph_number: Input should be greater than or equal to 1",
+ ),
+ ('{"video_subject": ', "body.18: JSON decode error"),
+ ],
+)
+def test_validation_message_describes_the_rejected_field(content, expected):
+ # Out-of-range values and malformed JSON used to be reported as
+ # "field required", pointing clients at a field that was present.
+ response = _post("/api/v1/scripts", content)
+
+ assert response.status_code == 400
+ body = response.json()
+ assert body["message"] == expected
+ assert body["data"][0]["msg"] in expected
+
+
+def test_missing_field_message_still_says_field_required():
+ response = _post("/api/v1/videos", "{}")
+
+ assert response.status_code == 400
+ assert response.json()["message"] == "body.video_subject: Field required"