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(_typename, _fields=None, /, **kwargs)¶
Bases:
TypedDict
Dictionary containing information on a link.
New in version 3.2.
- title: typing_extensions.NotRequired[str]¶
The optional title for the link.
This may not be present in the dictionary.
- Type:
- __annotations__ = {'href': ForwardRef('str'), 'method': ForwardRef('str'), 'title': ForwardRef('NotRequired[str]')}¶
- static __new__(cls, _typename, _fields=None, /, **kwargs)¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<class 'typing_extensions.TypedDict'>,)¶
- __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 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
.- api_data: WebAPIResponsePayload¶
The response payload that will be encoded.
This will be made up of both default and caller-provided data.
- 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:
- 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.
- request: HttpRequest¶
The HTTP request from the client.
- Type:
- __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.
- api_data: WebAPIResponsePayload¶
The response payload that will be encoded.
This will be made up of both default and caller-provided data.
- 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:
- 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.
- request: HttpRequest¶
The HTTP request from the client.
- Type:
- __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.