]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
:sparkles: By default, encode by alias (#168)
authorSebastián Ramírez <tiangolo@gmail.com>
Sat, 20 Apr 2019 16:29:54 +0000 (20:29 +0400)
committerGitHub <noreply@github.com>
Sat, 20 Apr 2019 16:29:54 +0000 (20:29 +0400)
fastapi/encoders.py
tests/test_jsonable_encoder.py

index ac3b317c6e16619114d78d61e6d48c44cd75e856..fc289c936f69373659cc0b16c6248570a92b666b 100644 (file)
@@ -10,7 +10,7 @@ def jsonable_encoder(
     obj: Any,
     include: Set[str] = None,
     exclude: Set[str] = set(),
-    by_alias: bool = False,
+    by_alias: bool = True,
     include_none: bool = True,
     custom_encoder: dict = {},
     sqlalchemy_safe: bool = True,
index 92eb34a785914f9bcd7a164858614ce116d90c5e..f079059edc3566cfb0ee4c4a608cdf53bd13ec66 100644 (file)
@@ -3,7 +3,7 @@ from enum import Enum
 
 import pytest
 from fastapi.encoders import jsonable_encoder
-from pydantic import BaseModel
+from pydantic import BaseModel, Schema, ValidationError
 
 
 class Person:
@@ -59,6 +59,10 @@ class ModelWithConfig(BaseModel):
         use_enum_values = True
 
 
+class ModelWithAlias(BaseModel):
+    foo: str = Schema(..., alias="Foo")
+
+
 def test_encode_class():
     person = Person(name="Foo")
     pet = Pet(owner=person, name="Firulais")
@@ -85,3 +89,13 @@ def test_encode_custom_json_encoders_model():
 def test_encode_model_with_config():
     model = ModelWithConfig(role=RoleEnum.admin)
     assert jsonable_encoder(model) == {"role": "admin"}
+
+
+def test_encode_model_with_alias_raises():
+    with pytest.raises(ValidationError):
+        model = ModelWithAlias(foo="Bar")
+
+
+def test_encode_model_with_alias():
+    model = ModelWithAlias(Foo="Bar")
+    assert jsonable_encoder(model) == {"Foo": "Bar"}