Skip to content

Commit

Permalink
request json is nullable
Browse files Browse the repository at this point in the history
  • Loading branch information
josesalasdev committed Apr 30, 2022
1 parent 6219b09 commit 16c1c8e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
4 changes: 2 additions & 2 deletions starlette/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,10 @@ async def body(self) -> bytes:
self._body = b"".join(chunks)
return self._body

async def json(self) -> typing.Any:
async def json(self, nullable: bool = False) -> typing.Any:
if not hasattr(self, "_json"):
body = await self.body()
self._json = json.loads(body)
self._json = {} if (body == b'' and nullable) else json.loads(body)
return self._json

async def form(self) -> FormData:
Expand Down
14 changes: 13 additions & 1 deletion tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,22 @@ async def app(scope, receive, send):
await response(scope, receive, send)

client = test_client_factory(app)
response = client.post("/", json={"a": "123"})
response = client.post("/", json={'a': '123'})
assert response.json() == {"json": {"a": "123"}}


def test_request_json_null(test_client_factory):
async def app(scope, receive, send):
request = Request(scope, receive)
data = await request.json(nullable=True)
response = JSONResponse({"json": data})
await response(scope, receive, send)

client = test_client_factory(app)
response = client.post("/")
assert response.json() == {"json": {}}


def test_request_scope_interface():
"""
A Request can be instantiated with a scope, and presents a `Mapping`
Expand Down

0 comments on commit 16c1c8e

Please sign in to comment.