Request-to-JSON Utilities

smarter.common.utils.request_to_json

Utility for converting Django ASGIRequest objects to JSON-serializable dictionaries.

This module provides the request_to_json function, which extracts relevant information from a Django ASGIRequest object (such as HTTP method, URL, and JSON body) and returns it as a dictionary suitable for serialization. If a dictionary or list is provided, it is returned as-is.

Example usage:

from smarter.common.utils import request_to_json
from django.core.handlers.asgi import ASGIRequest

# Example with ASGIRequest
request = ASGIRequest(...)
data = request_to_json(request)
print(data)

# Example with dictionary
data = request_to_json({"foo": "bar"})
print(data)  # Output: {'foo': 'bar'}
class smarter.common.utils.request_to_json.RequestData[source]

Bases: TypedDict

TypedDict representing the relevant data extracted from a request object.

body: dict[str, Any] | list[Any] | None
method: str
url: str
smarter.common.utils.request_to_json.request_to_json(request)[source]

Convert a Django ASGIRequest object, dictionary, or list to a JSON-serializable dictionary or list.

This function is primarily intended to extract relevant information from a Django ASGIRequest object (such as HTTP method, URL, and JSON body) and return it as a dictionary suitable for serialization. If a dictionary or list is provided, it is returned as-is.

Parameters:

request (ASGIRequest | dict | list) – The request object to convert. Can be a Django ASGIRequest, a dictionary, or a list.

Returns:

A JSON-serializable dictionary or list representing the request data.

Return type:

Union[RequestData, ASGIRequest, dict, list]

Note

  • If the request is an ASGIRequest, the function attempts to decode and parse the request body as JSON.

  • If the body cannot be parsed as JSON, the ‘body’ field will be set to None.

  • If the input is already a dictionary or list, it is returned unchanged.

Example usage:

from smarter.common.utils import request_to_json
from django.core.handlers.asgi import ASGIRequest

# Example with ASGIRequest
request = ASGIRequest(...)
data = request_to_json(request)
print(data)

# Example with dictionary
data = request_to_json({"foo": "bar"})
print(data)  # Output: {'foo': 'bar'}