diff --git a/.coverage.LAPTOP-7BUC2HHB.20644.XYqHRFXx b/.coverage.LAPTOP-7BUC2HHB.20644.XYqHRFXx new file mode 100644 index 000000000..daba3e9ed Binary files /dev/null and b/.coverage.LAPTOP-7BUC2HHB.20644.XYqHRFXx differ diff --git a/.gitignore b/.gitignore index ef6364a9a..cc3ac441c 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ archive.zip # macOS .DS_Store +.python-version diff --git a/fastapi/_compat.py b/fastapi/_compat.py index c07e4a3b0..8548109f8 100644 --- a/fastapi/_compat.py +++ b/fastapi/_compat.py @@ -92,7 +92,10 @@ if PYDANTIC_V2: @property def alias(self) -> str: - a = self.field_info.alias + a = ( + isinstance(self.field_info.validation_alias, str) + and self.field_info.validation_alias + ) or self.field_info.alias return a if a is not None else self.name @property @@ -277,7 +280,9 @@ if PYDANTIC_V2: def create_body_model( *, fields: Sequence[ModelField], model_name: str ) -> Type[BaseModel]: - field_params = {f.name: (f.field_info.annotation, f.field_info) for f in fields} + field_params = { + f"{f.alias}": (f.field_info.annotation, f.field_info) for f in fields + } BodyModel: Type[BaseModel] = create_model(model_name, **field_params) # type: ignore[call-overload] return BodyModel diff --git a/tests/test_alias_and_validation_alias_in_form.py b/tests/test_alias_and_validation_alias_in_form.py new file mode 100644 index 000000000..2454fe9dd --- /dev/null +++ b/tests/test_alias_and_validation_alias_in_form.py @@ -0,0 +1,58 @@ +""" +testing to fix incompatibility with alias and validation_alias between fastapi and PYDANTIC_V2 +""" + +from fastapi import FastAPI, Form +from fastapi._compat import PYDANTIC_V2 +from starlette.testclient import TestClient + +app: FastAPI = FastAPI() + + +@app.post("/testing_alias") +async def check_alias(id_test: int = Form(alias="otherId")): + return {"other_id": id_test} + + +@app.post("/testing_validation_alias") +async def check_validation_alias(id_test: int = Form(validation_alias="otherId")): + return {"other_id": id_test} + + +client = TestClient(app) + + +def test_get_alias(): + response = client.post("/testing_alias", data={"otherId": "1"}) + assert response.status_code == 200 + assert response.json() == {"other_id": 1} + + +def test_get_validation_alias(): + if PYDANTIC_V2: + data = {"otherId": "1"} + else: + data = {"id_test": "1"} + response = client.post("/testing_validation_alias", data=data) + assert response.status_code == 200 + assert response.json() == {"other_id": 1} + + +def test_file_alias_schema(): + response = client.get("/openapi.json") + assert response.status_code == 200, response.text + if PYDANTIC_V2: + schema = response.json() + assert ( + "otherId" + in schema["components"]["schemas"]["Body_check_alias_testing_alias_post"][ + "properties" + ] + ) + + assert ( + "otherId" + in schema["components"]["schemas"][ + "Body_check_validation_alias_testing_validation_alias_post" + ]["properties"] + )