Serializers
Serializers for Django HTTP requests and user objects in the Smarter API.
This module defines custom serializers for:
Serializing the User model for API responses.
Representing anonymous and authenticated HTTP request data for use with the Django REST Framework.
These serializers enable structured, validated, and documented representations of HTTP request and user data for API endpoints and internal processing.
- class smarter.lib.django.http.serializers.HttpAnonymousRequestSerializer(*args, **kwargs)[source]
Bases:
SerializerSerializes anonymous HTTP request data for the Smarter API.
This serializer is designed to represent the structure of an unauthenticated Django HTTP request, capturing key request attributes for use in API endpoints, logging, or debugging. It is intended for scenarios where user authentication is not required or available.
- Parameters:
url (str) – The absolute URL of the request (read-only, derived from the request object).
method (str) – The HTTP method (e.g.,
GET,POST,PUT,DELETE).GET (dict) – Query parameters from the request URL.
POST (dict) – Data submitted in the body of a POST request.
META (dict) – The request’s headers and metadata, limited to
SAFE_META_KEYS.body – The request’s body, parsed and with its credentials redacted (see
serialize_body()).path (str) – The path portion of the request URL.
encoding (str) – The encoding used for the request body.
content_type (str) – The MIME type of the request body.
Cookies are never serialized, and
METAkeeps onlySAFE_META_KEYS, because serialized requests are stored in the journal and must not hold API keys or session ids.Example
from smarter.lib.django.http.serializers import HttpAnonymousRequestSerializer from django.http import HttpRequest request = HttpRequest() request.method = "GET" request.path = "/api/v1/resource/" request.GET = {"search": "test"} request.encoding = "utf-8" request.content_type = "application/json" serializer = HttpAnonymousRequestSerializer(request) print(serializer.data) # Output (example): # { # 'url': None, # 'method': 'GET', # 'GET': {'search': 'test'}, # 'POST': {}, # 'META': {}, # 'path': '/api/v1/resource/', # 'encoding': 'utf-8', # 'content_type': 'application/json' # }
Note
The
urlfield is computed from the request object if available. If the request does not provide a method for building the absolute URI, this field may beNone.Warning
This serializer does not include user authentication information. For authenticated requests, use
HttpAuthenticatedRequestSerializer.- create(validated_data)[source]
Build a new, unsaved
HttpRequestfrom the validated data.- Parameters:
validated_data – The request attributes to set.
- Return type:
- Returns:
The request.
- get_META(obj)[source]
Return the request’s
META, limited toSAFE_META_KEYS.
- get_body(obj)[source]
Return the request’s body, parsed and with its credentials redacted.
- Parameters:
obj (
HttpRequest) – The request.- Return type:
JsonValue- Returns:
See
serialize_body().
- to_representation(instance)[source]
Serialize the request, adding its absolute
url.- Parameters:
instance – The request.
- Returns:
The serialized request.
- update(instance, validated_data)[source]
Set the validated data’s attributes on an existing request.
- Parameters:
instance (
HttpRequest) – The request to change.validated_data – The request attributes to set.
- Returns:
The same request.
- class smarter.lib.django.http.serializers.HttpAuthenticatedRequestSerializer(*args, **kwargs)[source]
Bases:
HttpAnonymousRequestSerializerSerializes authenticated HTTP request data for the Smarter API.
This serializer extends
HttpAnonymousRequestSerializerto include user information, allowing for the representation of authenticated Django HTTP requests. It is intended for use in API endpoints, logging, or debugging where both request and user context are required.- Parameters:
url (str) – The absolute URL of the request (read-only, derived from the request object).
method (str) – The HTTP method (e.g.,
GET,POST,PUT,DELETE).GET (dict) – Query parameters from the request URL.
POST (dict) – Data submitted in the body of a POST request.
META (dict) – The request’s headers and metadata, limited to
SAFE_META_KEYS.path (str) – The path portion of the request URL.
encoding (str) – The encoding used for the request body.
content_type (str) – The MIME type of the request body.
user – The authenticated user making the request, serialized using
UserSerializer.
Example
from smarter.lib.django.http.serializers import HttpAuthenticatedRequestSerializer from django.http import HttpRequest from smarter.apps.account.models import User request = HttpRequest() request.method = "POST" request.path = "/api/v1/secure/" request.POST = {"data": "value"} request.encoding = "utf-8" request.content_type = "application/json" request.user = User(username="bob") serializer = HttpAuthenticatedRequestSerializer(request) print(serializer.data) # Output (example): # { # 'url': None, # 'method': 'POST', # 'GET': {}, # 'POST': {'data': 'value'}, # 'META': {}, # 'path': '/api/v1/secure/', # 'encoding': 'utf-8', # 'content_type': 'application/json', # 'user': 'bob' # }
Note
The
userfield is serialized usingUserSerializerand only exposes the username by default.Warning
Ensure that sensitive user information is not exposed by extending
UserSerializerwith caution. This serializer should only be used in contexts where authenticated user data is appropriate.
- smarter.lib.django.http.serializers.JSON_VALUE: TypeAdapter[JsonValue] = TypeAdapter(JsonValue)
Validates a parsed request body as JSON.
- smarter.lib.django.http.serializers.MAX_SERIALIZED_BODY_SIZE = 1048576
The largest request body, in bytes, that a serialized request keeps.
A larger one is replaced by its size.
- smarter.lib.django.http.serializers.REDACTED_VALUE = '********'
What a credential in a serialized request body is replaced with.
- smarter.lib.django.http.serializers.SAFE_META_KEYS = frozenset({'CONTENT_LENGTH', 'CONTENT_TYPE', 'HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_HOST', 'HTTP_ORIGIN', 'HTTP_REFERER', 'HTTP_USER_AGENT', 'HTTP_X_FORWARDED_FOR', 'PATH_INFO', 'QUERY_STRING', 'REMOTE_ADDR', 'REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT'})
The
request.METAkeys that a serialized request keeps.Serialized requests are stored in the journal, so this is an allowlist: headers that carry credentials (
HTTP_AUTHORIZATION,HTTP_COOKIE,HTTP_X_CSRFTOKEN), and the server’s own environment, are never stored.
- smarter.lib.django.http.serializers.SENSITIVE_BODY_KEYS = frozenset({'access_key', 'api_key', 'apikey', 'authorization', 'client_secret', 'credentials', 'csrfmiddlewaretoken', 'passwd', 'password', 'private_key', 'secret', 'secret_key', 'session_key', 'sessionid', 'token'})
The keys, in snake_case, whose values a serialized request body never keeps.
A key is also sensitive when it ends in
_and one of these, e.g.proxyPasswordoraws_secret_access_key. Keys are matched whole, not as substrings, so that usage counters such asmax_tokensare kept.
- class smarter.lib.django.http.serializers.UserSerializer(*args, **kwargs)[source]
Bases:
ModelSerializerSerializes the
Usermodel for use in Django REST Framework APIs.This serializer provides a minimal representation of the
Userobject, exposing only theusernamefield. It is intended for use in API responses where user identification is required, but sensitive information should be excluded.- Parameters:
username (str) – The unique username of the user.
Example
from smarter.lib.django.http.serializers import UserSerializer from smarter.apps.account.models import User user = User(username="alice") serializer = UserSerializer(user) print(serializer.data) # Output: {'username': 'alice'}
Note
This serializer is designed to be minimal for privacy and security. Only the
usernamefield is exposed.Warning
Do not extend this serializer to include sensitive fields (such as passwords or email addresses) unless absolutely necessary and with proper security considerations.
- smarter.lib.django.http.serializers.is_sensitive_body_key(key)[source]
Return whether a request body’s key names a credential.
- Parameters:
key (
str) – The key, in snake_case, camelCase or kebab-case.- Return type:
- Returns:
True if the key, or its last
_-separated suffix, is inSENSITIVE_BODY_KEYS.
- smarter.lib.django.http.serializers.parse_body_text(text)[source]
Parse a request body’s text as JSON, or else as YAML, e.g. a manifest.
- Parameters:
text (
str) – The body’s text.- Return type:
JsonValue- Returns:
The parsed value, or the text itself if it is neither, or is YAML that isn’t JSON, e.g. with a date or an integer key.
- smarter.lib.django.http.serializers.read_body(request)[source]
Return a request’s raw body.
- Parameters:
request (
HttpRequest) – The request.- Return type:
- Returns:
The body, or empty bytes if it has none, or it was read as a stream, e.g. a file upload.
- smarter.lib.django.http.serializers.redact_body(value)[source]
Return a copy of a parsed request body, with its credentials replaced by
REDACTED_VALUE.A value is replaced when its key is sensitive (see
is_sensitive_body_key()), and a Secret manifest’sspec.config.valueis always replaced.- Parameters:
value (
JsonValue) – The parsed body, or a part of it.- Return type:
JsonValue- Returns:
The redacted copy.
- smarter.lib.django.http.serializers.serialize_body(request)[source]
Return a request’s body, parsed and redacted, for the journal.
A JSON or YAML body is returned parsed, other text as it is, and a binary or larger than
MAX_SERIALIZED_BODY_SIZEbody only as its size. Credentials are replaced byredact_body(); text that can’t be parsed can’t be redacted, and is kept only if it has no sensitive key in it.- Parameters:
request (
HttpRequest) – The request.- Return type:
JsonValue- Returns:
The body, None if there is none or it can’t be read, or
{"size": n}.