Skip to content
This repository was archived by the owner on Nov 19, 2024. It is now read-only.

Commit 5d8b75d

Browse files
committed
Added doc and test for JSON overwrite of url params
1 parent a167f65 commit 5d8b75d

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

flask_utils/decorators.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,33 @@ def example(name: str, age: int, is_student: bool, courses: List[str], grades: D
215215
* Optional
216216
* Union
217217
218+
.. warning::
219+
If a parameter exists both in the route parameters and in the JSON body,
220+
the value from the JSON body will override the route parameter. A warning
221+
is issued when this occurs.
222+
223+
:Example:
224+
225+
.. code-block:: python
226+
227+
from flask import Flask, request
228+
from typing import List, Dict
229+
from flask_utils.decorators import validate_params
230+
from flask_utils.errors import BadRequestError
231+
232+
app = Flask(__name__)
233+
234+
@app.route("/users/<int:user_id>", methods=["POST"])
235+
@validate_params()
236+
def create_user(user_id: int):
237+
print(f"User ID: {user_id}")
238+
return "User created"
239+
240+
...
241+
242+
requests.post("/users/123", json={"user_id": 456})
243+
# Output: User ID: 456
244+
218245
.. versionchanged:: 1.0.0
219246
The decorator doesn't take any parameters anymore,
220247
it loads the types and parameters from the function signature as well as the Flask route's slug parameters.

tests/test_validate_params.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,3 +565,17 @@ def test_max_depth(self, client):
565565
assert len(w) == 1
566566
assert issubclass(w[-1].category, SyntaxWarning)
567567
assert "Maximum depth of 4 reached." in str(w[-1].message)
568+
569+
570+
class TestJSONOverridesRouteParams:
571+
@pytest.fixture(autouse=True)
572+
def setup_routes(self, flask_client):
573+
@flask_client.post("/users/<int:user_id>")
574+
@validate_params()
575+
def create_user(user_id: int):
576+
return f"{user_id}"
577+
578+
def test_valid_request(self, client):
579+
response = client.post("/users/123", json={"user_id": 456})
580+
assert response.status_code == 200
581+
assert response.text == "456"

0 commit comments

Comments
 (0)