djblets.webapi.responses¶
HTTP responses for Web APIs.
- WebAPIResponseHeaders¶
A dictionary of headers to return from the API.
New in version 3.2.
- class WebAPIResponseLink¶
Bases:
TypedDict
Dictionary containing information on a link.
New in version 3.2.
- href: Optional[str]¶
The absolute URL that the link points to.
This may be None in the case of an error generating a link, such as due to a circular dependency.
Changed in version 4.0: This can now be
None
.- Type:
- __annotations__ = {'href': ForwardRef('Optional[str]', module='djblets.webapi.responses'), 'method': ForwardRef('str', module='djblets.webapi.responses'), 'title': ForwardRef('NotRequired[str]', module='djblets.webapi.responses')}¶
- __closed__ = False¶
- __extra_items__ = None¶
- __mutable_keys__ = frozenset({'href', 'method', 'title'})¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<function TypedDict>,)¶
- __readonly_keys__ = frozenset({})¶
- __required_keys__ = frozenset({'href', 'method', 'title'})¶
- __total__ = True¶
- WebAPIResponseLinks¶
A type alias for a mapping of link names to link information.
New in version 3.2.
alias of
Dict
[str
,WebAPIResponseLink
]
- WebAPIResponsePayload¶
A type alias for an API response payload.
New in version 3.2.
- class WebAPIEventStreamMessage¶
Bases:
EventStreamMessage
A message generated in an API event stream.
This is used by
WebAPIResponseEventStream
to stream data to a client.A message may contain an ID, application-defined event type, serialized payload data (which may be a serialized object payload or may be custom text-based data), and a retry time in milliseconds. These are all optional, but any empty message will be skipped.
New in version 4.0.
- stat: str¶
The value for the API response payload’s
stat
key.If not provided, this will default to “ok”.
- Type:
- __annotations__ = {'data': ForwardRef('NotRequired[Optional[Union[bytes, str]]]', module='djblets.http.responses'), 'event': ForwardRef('NotRequired[Optional[str]]', module='djblets.http.responses'), 'id': ForwardRef('NotRequired[Optional[str]]', module='djblets.http.responses'), 'obj': ForwardRef('NotRequired[WebAPIResponsePayload]', module='djblets.webapi.responses'), 'retry_ms': ForwardRef('NotRequired[Optional[int]]', module='djblets.http.responses'), 'stat': ForwardRef('NotRequired[str]', module='djblets.webapi.responses')}¶
- __closed__ = False¶
- __extra_items__ = None¶
- __mutable_keys__ = frozenset({'data', 'event', 'id', 'obj', 'retry_ms', 'stat'})¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<class 'djblets.http.responses.EventStreamMessage'>,)¶
- __readonly_keys__ = frozenset({})¶
- __required_keys__ = frozenset({'data', 'event', 'id', 'obj', 'retry_ms', 'stat'})¶
- __total__ = True¶
- WebAPIEventStreamMessages¶
An iterator for API event stream messages.
New in version 4.0.
alias of
Iterator
[WebAPIEventStreamMessage
]
- WebAPIEventStream¶
An API event stream that generates messages.
This may be an iterator of messages, or a callable that takes an optional Last-Event-ID header value and then yields messages.
New in version 4.0.
alias of
Union
[Iterator
[WebAPIEventStreamMessage
],Callable
[[Optional
[str
]],Iterator
[WebAPIEventStreamMessage
]]]
- class WebAPIResponse(request: HttpRequest, *, obj: WebAPIResponsePayload = {}, stat: str = 'ok', api_format: Optional[str] = None, status: int = 200, headers: WebAPIResponseHeaders = {}, encoders: Sequence[WebAPIEncoder] = [], encoder_kwargs: Dict[str, Any] = {}, mimetype: Optional[str] = None, supported_mimetypes: Optional[List[str]] = None)¶
Bases:
HttpResponse
An API response, formatted for the desired file format.
- supported_mimetypes: List[str] = ['application/json', 'application/xml']¶
The default list of supported mimetypes for the payload.
- __init__(request: HttpRequest, *, obj: WebAPIResponsePayload = {}, stat: str = 'ok', api_format: Optional[str] = None, status: int = 200, headers: WebAPIResponseHeaders = {}, encoders: Sequence[WebAPIEncoder] = [], encoder_kwargs: Dict[str, Any] = {}, mimetype: Optional[str] = None, supported_mimetypes: Optional[List[str]] = None) None ¶
Initialize the response.
This will attempt to automatically determine the resulting mimetype, if
mimetype
is not provided.If
api_format
is provided (as an argument to this function, through theapi_format=
query string for GET requests, or through a field for POST/PUT requests), it will be used to try to guess the mimetype.If one cannot be determined through those values, the Accept HTTP header will be used instead.
Finally, if no mimetype can be determined, no content will be generated and this will automatically be set to a HTTP 400 Bad Request.
Changed in version 3.2: All arguments (except for
request
) must now be provided as keywords.- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.obj (
dict
, optional) –The object payload to serializle.
Contents depends on the
encoder
.stat (
str
, optional) – The value for the API response payload’sstat
key.api_format (
str
, optional) – An explicit format for the result payload, used to determine a default formimetype
.status (
int
, optional) – The HTTP status code for the response.headers (
dict
, optional) – Custom HTTP headers to include in the response.encoders (
list
ofdjblets.webapi.encoders.WebAPIEncoder
, optional) –The list of encoders available to encode
obj
.If not provided, all registered encoders will be tried. See
get_registered_encoders()
.encoder_kwargs (
dict
, optional) – Keyword arguments to pass when instantiating encoders.mimetype (
str
, optional) – An explicit mimetype to use for the result.supported_mimetypes (
list
ofstr
, optional) –A list of supported mimetypes for this response.
This is used when trying to guess a mimetype from the Accept header.
- request: HttpRequest¶
The HTTP request from the client.
- Type:
- callback: Optional[str]¶
A JSONP callback provided in GET requests.
This will be set if the caller specifies
?callback=...
. Otherwise, it will beNone
.- Type:
- api_data: WebAPIResponsePayload¶
The response payload that will be encoded.
This will be made up of both default and caller-provided data.
- Type:
- content_set: bool¶
Whether
content
has been computed for the final result.This is mostly an implementation detail, but is available to outside callers to know when the content is finalized.
- Type:
- encoders: Sequence[WebAPIEncoder]¶
The list of encoders that can be used to try to encode the payload.
- property content: bytes¶
The encoded API response content.
This is an overridden version of
HttpResponse._get_content()
that generates the resulting content when requested, rather than generating it up-front in the constructor, allowing data to be updated after construction but before it’s ready to be sent to the client.- Type:
- __annotations__ = {'api_data': 'WebAPIResponsePayload', 'callback': 'Optional[str]', 'content_set': 'bool', 'encoder_kwargs': 'Dict[str, Any]', 'encoders': 'Sequence[WebAPIEncoder]', 'mimetype': 'str', 'request': 'HttpRequest', 'supported_mimetypes': 'List[str]'}¶
- class WebAPIResponsePaginated(request: HttpRequest, *args, queryset: Optional[QuerySet] = None, results_key: str = 'results', prev_key: str = 'prev', next_key: str = 'next', total_results_key: str = 'total_results', start_param: str = 'start', max_results_param: str = 'max-results', default_start: int = 0, default_max_results: int = 25, max_results_cap: int = 200, serialize_object_func: Optional[Callable[[object], Any]] = None, extra_data: Dict[Any, Any] = {}, **kwargs)¶
Bases:
WebAPIResponse
A response containing a list of results with pagination.
This accepts the following parameters to the URL:
start - The index of the first item (0-based index).
max-results - The maximum number of results to return in the request.
Subclasses can override much of the pagination behavior of this function. While the default behavior operates on a queryset and works on indexes within that queryset, subclasses can override this to work on any data and paginate in any way they see fit.
- __init__(request: HttpRequest, *args, queryset: Optional[QuerySet] = None, results_key: str = 'results', prev_key: str = 'prev', next_key: str = 'next', total_results_key: str = 'total_results', start_param: str = 'start', max_results_param: str = 'max-results', default_start: int = 0, default_max_results: int = 25, max_results_cap: int = 200, serialize_object_func: Optional[Callable[[object], Any]] = None, extra_data: Dict[Any, Any] = {}, **kwargs) None ¶
Initialize the response.
Changed in version 3.2: All arguments (except for
request
) must now be provided as keywords.- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.*args (
tuple
) –Positional arguments to pass to the parent class.
This is only for backwards-compatibility, and will be removed in Djblets 4.0.
queryset (
django.db.models.QuerySet
, optional) – The optional queryset used to construct these results.results_key (
str
, optional) – The name of the key used to store the resulting list of items.prev_key (
str
, optional) – The key used for the previous results link in the payload.next_key (
str
, optional) – The key used for the next results link in the payload.total_results_key (
str
, optional) – The key used for the total results count in the payload.start_param (
str
, optional) – The query argument key requesting the start offset.max_results_param (
str
, optional) – The query argument key requesting the maximum number of results.default_start (
int
, optional) – The default start offset, if not provided in the request usingstart_param
.default_max_results (
int
, optional) – The default maximum number of results, if not provided in the request usingmax_results_param
.max_results_cap (
int
, optional) –The maximum number of results allowed in a response.
Any user-requested max will be capped to this value.
serialize_object_func (
callable
, optional) – A function to call to serialize a single result.extra_data (
dict
, optional) – Extra payload data to merge into the resulting payload.**kwargs (
dict
) – Keyword arguments to pass to the parent class.
- queryset: Optional[QuerySet]¶
The optional queryset used to construct these results.
- Type:
django.db.models.QuerySet
- __annotations__ = {'api_data': 'WebAPIResponsePayload', 'callback': 'Optional[str]', 'content_set': 'bool', 'encoder_kwargs': 'Dict[str, Any]', 'encoders': 'Sequence[WebAPIEncoder]', 'max_results': 'int', 'max_results_param': 'str', 'mimetype': 'str', 'next_key': 'str', 'prev_key': 'str', 'queryset': 'Optional[QuerySet]', 'request': 'HttpRequest', 'results': 'Collection[Any]', 'start': 'int', 'start_param': 'str', 'supported_mimetypes': 'List[str]', 'total_results_key': 'str'}¶
- results: Collection[Any]¶
The results to return.
- normalize_start(start: Union[int, str]) int ¶
Normalize the start value.
By default, this ensures it’s an integer no less than 0. Subclasses can override this behavior.
- has_prev() bool ¶
Return whether there’s a previous set of results.
- Returns:
True
if there’s a previous set of results.False
if there is not.- Return type:
- has_next() bool ¶
Return whether there’s a next set of results.
- Returns:
True
if there’s a next set of results.False
if there is not.- Return type:
- get_prev_index() int ¶
Return the previous index to use for ?start=
- Returns:
The previous index. This will never be less than 0.
- Return type:
- get_next_index() int ¶
Return the next index to use for ?start=
- Returns:
The next index.
- Return type:
- get_results() Collection[Any] ¶
Return the results for this page.
- Returns:
The collection of results from the queryset.
- Return type:
- get_total_results() int ¶
Return the total number of results across all pages.
Subclasses can return
None
to prevent this field from showing up in the payload.- Returns:
The number of resulting items.
- Return type:
- get_links() Dict[str, WebAPIResponseLink] ¶
Return all links used in the payload.
By default, this only includes pagination links. Subclasses can provide additional links.
- Returns:
The dictionary mapping link names to link information.
See
WebAPIResponseLinkDict
for the format of the link information dictionaries.- Return type:
- class WebAPIResponseError(request: HttpRequest, err: WebAPIError, *args, extra_params: Dict[Any, Any] = {}, headers: WebAPIResponseHeaders = {}, **kwargs)¶
Bases:
WebAPIResponse
A general API error response.
This contains an error code and a human-readable message. Additional data can be provided through
extra_params
andheaders
.- __annotations__ = {}¶
- __init__(request: HttpRequest, err: WebAPIError, *args, extra_params: Dict[Any, Any] = {}, headers: WebAPIResponseHeaders = {}, **kwargs) None ¶
Initialize the response.
Changed in version 3.2: All arguments (except for
request
) must now be provided as keywords.- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.err (
djblets.webapi.errors.WebAPIError
) – The error class to use for the response.*args (
tuple
) –Positional arguments to pass to the parent class.
This is only for backwards-compatibility, and will be removed in Djblets 4.0.
extra_params (
dict
, optional) –Additional data to include in the root of the payload.
This should not include an
err
key.headers (
dict
, optional) – Custom HTTP headers to include in the response.**kwargs (
dict
) – Keyword arguments to pass to the parent class.
- class WebAPIResponseFormError(request: HttpRequest, form: Form, *args, **kwargs)¶
Bases:
WebAPIResponseError
An error response designed to return all errors from a form.
- __annotations__ = {}¶
- __init__(request: HttpRequest, form: Form, *args, **kwargs) None ¶
Initialize the response.
Changed in version 3.2: All arguments (except for
request
) must now be provided as keywords.- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.form (
django.forms.Form
) – The form class to represent in the response.*args (
tuple
) –Positional arguments to pass to the parent class.
This is only for backwards-compatibility, and will be removed in Djblets 4.0.
**kwargs (
dict
) – Keyword arguments to pass to the parent class.
- class WebAPIResponseEventStream(event_stream: WebAPIEventStream, *, request: HttpRequest, api_format: Optional[str] = None, status: int = 200, headers: WebAPIResponseHeaders = {}, encoders: Sequence[WebAPIEncoder] = [], encoder_kwargs: Dict[str, Any] = {}, message_data_mimetype: Optional[str] = None, supported_mimetypes: Optional[List[str]] = None)¶
Bases:
EventStreamHttpResponse
A Server-Sent Events (SSE) API response.
This is a specialization of
EventStreamHttpResponse
built to serialize API responses as part of Server-Sent Events. This enables standard API responses to be serialized as results from an event stream, useful for streaming progress updates or batched API call results as part of an API call.By default, each Server-Sent Event will contain API payload data containing, at a minimum, a standard
"stat": "ok"
field. This can be extended by specifying an object payload. The serialized result of the payload will be in JSON format by default, but this can be controlled through the standard Accept header orapi_format
argument.The mimetype for standard data payloads (for entries without an
event
type or withevent: message
, the spec-provided default) will be sent in X-Event-Data-Mimetype.New in version 4.0.
- __annotations__ = {}¶
- __init__(event_stream: WebAPIEventStream, *, request: HttpRequest, api_format: Optional[str] = None, status: int = 200, headers: WebAPIResponseHeaders = {}, encoders: Sequence[WebAPIEncoder] = [], encoder_kwargs: Dict[str, Any] = {}, message_data_mimetype: Optional[str] = None, supported_mimetypes: Optional[List[str]] = None) None ¶
Initialize the API event stream.
The provided API event stream source will be processed when sending content to the client, and not before.
- Parameters:
event_stream (
callable
orgenerator
) – The event stream as a generator or a callable yielding results.request (
django.http.HttpRequest
, optional) – The HTTP request from the client.api_format (
str
, optional) – An explicit format for the result payload, used to determine a default formessage_data_mimetype
.status (
int
, optional) – The HTTP status code to send in the response.headers (
dict
, optional) – Custom HTTP headers to include in the response.encoders (
list
ofdjblets.webapi.encoders.WebAPIEncoder
, optional) –The list of encoders available to encode object payloads.
If not provided, all registered encoders will be tried. See
get_registered_encoders()
.encoder_kwargs (
dict
, optional) – Keyword arguments to pass when instantiating encoders.message_data_mimetype (
str
, optional) –The mimetype for the standard message data payloads.
If not provided, one will be automatically determined based on
api_format
and the request mimetype.supported_mimetypes (
list
ofstr
, optional) –A list of supported mimetypes for this response.
This is used when trying to guess a mimetype from the Accept header.