• Get Review Board
  • What's New
  • Products
  • Review Board Code review, image review, and document review
  • Documentation
  • Release Notes
  • Power Pack Enterprise integrations, reports, and enhanced document review
  • Try for 60 Days
  • Purchase
  • RBCommons Review Board as a Service, hosted by us
  • Pricing
  • RBTools Command line tools and Python API for Review Board
  • Documentation
  • Release Notes
  • Review Bot Automated code review, connecting tools you already use
  • Documentation
  • Release Notes
  • RB Gateway Manage Git and Mercurial repositories in your network
  • Documentation
  • Release Notes
  • Learn and Explore
  • What is Code Review?
  • Documentation
  • Frequently Asked Questions
  • Support Options
  • Third-Party Integrations
  • Demo
  • Review Board RBTools Power Pack Review Bot Djblets RB Gateway
    1. Djblets 4.x
    2. Version 5.x
    3. Version 4.x
    4. Version 3.x
    5. Version 2.x
    6. Version 2.0
    7. Version 1.0
    8. Version 0.9
    9. Djblets Documentation
    10. Module and Class References
    11. djblets.webapi.resources.base
  • Home
  • Guides
  • Avatar Services Guides
  • Writing Avatar Services
  • Extension Guides
  • Writing Extensions
  • Testing Extensions
  • Feature Checks Guides
  • Introduction to Feature Checks
  • Writing Features
  • Writing Feature Checkers
  • Testing with Feature Checks
  • Integration Guides
  • Supporting Integrations
  • Writing Integrations
  • Privacy Compliance Guides
  • Getting and Checking Consent
  • Working with Personally Identifiable Information
  • Service Integrations
  • reCAPTCHA Guides
  • Using reCAPTCHA
  • Registries Guides
  • Writing Registries
  • Web API Guides
  • Writing Web API Resources
  • Adding OAuth2 Support
  • Module and Class References
  • djblets
  • djblets.deprecation
  • djblets.auth.forms
  • djblets.auth.ratelimit
  • djblets.auth.signals
  • djblets.auth.util
  • djblets.auth.views
  • djblets.avatars.errors
  • djblets.avatars.forms
  • djblets.avatars.registry
  • djblets.avatars.services
  • djblets.avatars.services.base
  • djblets.avatars.services.fallback
  • djblets.avatars.services.file_upload
  • djblets.avatars.services.gravatar
  • djblets.avatars.services.url
  • djblets.avatars.settings
  • djblets.cache.backend
  • djblets.cache.backend_compat
  • djblets.cache.context_processors
  • djblets.cache.errors
  • djblets.cache.forwarding_backend
  • djblets.cache.serials
  • djblets.cache.synchronizer
  • djblets.conditions
  • djblets.conditions.choices
  • djblets.conditions.conditions
  • djblets.conditions.errors
  • djblets.conditions.operators
  • djblets.conditions.values
  • djblets.configforms.forms
  • djblets.configforms.mixins
  • djblets.configforms.pages
  • djblets.configforms.registry
  • djblets.configforms.views
  • djblets.datagrid.grids
  • djblets.db.backends.mysql.base
  • djblets.db.fields
  • djblets.db.fields.base64_field
  • djblets.db.fields.counter_field
  • djblets.db.fields.json_field
  • djblets.db.fields.modification_timestamp_field
  • djblets.db.fields.relation_counter_field
  • djblets.db.managers
  • djblets.db.query
  • djblets.db.validators
  • djblets.extensions.admin
  • djblets.extensions.errors
  • djblets.extensions.extension
  • djblets.extensions.forms
  • djblets.extensions.hooks
  • djblets.extensions.loaders
  • djblets.extensions.manager
  • djblets.extensions.middleware
  • djblets.extensions.models
  • djblets.extensions.packaging
  • djblets.extensions.resources
  • djblets.extensions.settings
  • djblets.extensions.signals
  • djblets.extensions.staticfiles
  • djblets.extensions.testing
  • djblets.extensions.testing.testcases
  • djblets.extensions.urls
  • djblets.extensions.views
  • djblets.extensions.templatetags.djblets_extensions
  • djblets.features
  • djblets.features.checkers
  • djblets.features.decorators
  • djblets.features.errors
  • djblets.features.feature
  • djblets.features.level
  • djblets.features.registry
  • djblets.features.testing
  • djblets.features.templatetags.features
  • djblets.feedview.views
  • djblets.feedview.templatetags.feedtags
  • djblets.forms.fields
  • djblets.forms.fieldsets
  • djblets.forms.forms
  • djblets.forms.forms.key_value_form
  • djblets.forms.widgets
  • djblets.gravatars
  • djblets.gravatars.templatetags.gravatars
  • djblets.http.middleware
  • djblets.http.responses
  • djblets.integrations.errors
  • djblets.integrations.forms
  • djblets.integrations.hooks
  • djblets.integrations.integration
  • djblets.integrations.manager
  • djblets.integrations.mixins
  • djblets.integrations.models
  • djblets.integrations.urls
  • djblets.integrations.views
  • djblets.log
  • djblets.log.middleware
  • djblets.log.siteconfig
  • djblets.log.urls
  • djblets.log.views
  • djblets.mail.dmarc
  • djblets.mail.message
  • djblets.mail.testing
  • djblets.mail.utils
  • djblets.markdown
  • djblets.markdown.extensions.escape_html
  • djblets.markdown.extensions.wysiwyg
  • djblets.markdown.extensions.wysiwyg_email
  • djblets.pipeline.compilers.es6
  • djblets.pipeline.compilers.less
  • djblets.pipeline.compilers.mixins
  • djblets.pipeline.compilers.rollup
  • djblets.pipeline.compilers.typescript
  • djblets.pipeline.settings
  • djblets.privacy.consent
  • djblets.privacy.consent.base
  • djblets.privacy.consent.common
  • djblets.privacy.consent.errors
  • djblets.privacy.consent.forms
  • djblets.privacy.consent.hooks
  • djblets.privacy.consent.registry
  • djblets.privacy.consent.tracker
  • djblets.privacy.models
  • djblets.privacy.pii
  • djblets.privacy.templatetags.djblets_privacy
  • djblets.recaptcha.mixins
  • djblets.recaptcha.siteconfig
  • djblets.recaptcha.templatetags.djblets_recaptcha
  • djblets.recaptcha.widgets
  • djblets.registries
  • djblets.registries.errors
  • djblets.registries.importer
  • djblets.registries.mixins
  • djblets.registries.registry
  • djblets.registries.signals
  • djblets.secrets
  • djblets.secrets.crypto
  • djblets.secrets.token_generators
  • djblets.secrets.token_generators.base
  • djblets.secrets.token_generators.legacy_sha1
  • djblets.secrets.token_generators.registry
  • djblets.secrets.token_generators.vendor_checksum
  • djblets.siteconfig
  • djblets.siteconfig.admin
  • djblets.siteconfig.context_processors
  • djblets.siteconfig.django_settings
  • djblets.siteconfig.forms
  • djblets.siteconfig.managers
  • djblets.siteconfig.middleware
  • djblets.siteconfig.models
  • djblets.siteconfig.signals
  • djblets.siteconfig.views
  • djblets.template.caches
  • djblets.template.context
  • djblets.template.loaders.conditional_cached
  • djblets.template.loaders.namespaced_app_dirs
  • djblets.testing.decorators
  • djblets.testing.testcases
  • djblets.testing.testrunners
  • djblets.urls.context_processors
  • djblets.urls.decorators
  • djblets.urls.patterns
  • djblets.urls.resolvers
  • djblets.urls.root
  • djblets.urls.staticfiles
  • djblets.util.compat.django.core.cache
  • djblets.util.compat.python.past
  • djblets.util.contextmanagers
  • djblets.util.dates
  • djblets.util.decorators
  • djblets.util.filesystem
  • djblets.util.functional
  • djblets.util.html
  • djblets.util.http
  • djblets.util.humanize
  • djblets.util.json_utils
  • djblets.util.properties
  • djblets.util.serializers
  • djblets.util.symbols
  • djblets.util.templatetags.djblets_deco
  • djblets.util.templatetags.djblets_email
  • djblets.util.templatetags.djblets_forms
  • djblets.util.templatetags.djblets_images
  • djblets.util.templatetags.djblets_js
  • djblets.util.templatetags.djblets_utils
  • djblets.util.typing
  • djblets.util.views
  • djblets.views.generic.base
  • djblets.views.generic.etag
  • djblets.webapi.auth
  • djblets.webapi.auth.backends
  • djblets.webapi.auth.backends.api_tokens
  • djblets.webapi.auth.backends.base
  • djblets.webapi.auth.backends.basic
  • djblets.webapi.auth.backends.oauth2_tokens
  • djblets.webapi.auth.views
  • djblets.webapi.decorators
  • djblets.webapi.encoders
  • djblets.webapi.errors
  • djblets.webapi.fields
  • djblets.webapi.managers
  • djblets.webapi.models
  • djblets.webapi.oauth2_scopes
  • djblets.webapi.resources
  • djblets.webapi.resources.base
  • djblets.webapi.resources.group
  • djblets.webapi.resources.registry
  • djblets.webapi.resources.root
  • djblets.webapi.resources.user
  • djblets.webapi.resources.mixins.api_tokens
  • djblets.webapi.resources.mixins.forms
  • djblets.webapi.resources.mixins.oauth2_tokens
  • djblets.webapi.resources.mixins.queries
  • djblets.webapi.responses
  • djblets.webapi.signals
  • djblets.webapi.testing
  • djblets.webapi.testing.decorators
  • djblets.webapi.testing.testcases
  • General Index
  • Python Module Index
  • Release Notes
  • This documentation covers Djblets 4.x. You can select a version above or view the latest documentation.

    djblets.webapi.resources.base¶

    Base class for a resource in an API.

    WebAPIResourceHandlerResult¶

    The result from an API method handler.

    API method handlers may return HTTP responses, API responses, API errors, or tuples.

    Tuples may contain API errors or HTTP status codes, payloads or event streams, and optional headers.

    New in version 4.0.

    alias of Union[HttpResponseBase, Tuple[WebAPIError, Dict[Any, Any], Dict[str, str]], Tuple[WebAPIError, Dict[Any, Any]], Tuple[int, Union[Dict[Any, Any], Iterator[WebAPIEventStreamMessage], Callable[[Optional[str]], Iterator[WebAPIEventStreamMessage]]], Dict[str, str]], Tuple[int, Union[Dict[Any, Any], Iterator[WebAPIEventStreamMessage], Callable[[Optional[str]], Iterator[WebAPIEventStreamMessage]]]], WebAPIError, WebAPIResponse]

    class WebAPIResourceFieldInfo[source]¶

    Bases: TypedDict

    Information on a field in a serialized API payload.

    New in version 4.0.

    description: str¶

    A description of the field.

    This is in ReStructuredText format, and is intended for documentation generation.

    Type

    str

    type: Union[Type[BaseAPIFieldType], Type[bytes], Type[str], Type[bool], Type[int], Sequence[str]]¶

    The type of field.

    This should be a BaseAPIFieldType subclass.

    For backwards-compatibiltiy, str, bytes, bool, int, or a list, or :py:class:`tuple of string values can be specified, but these are considered legacy.

    added_in: NotRequired[str]¶

    The version of the product the field was added in.

    Type:

    str

    choices: Sequence[str]¶
    deprecated_in: NotRequired[str]¶

    The version of the product the field was deprecated in.

    Type:

    str

    resource: NotRequired[Union[str, Type[WebAPIResource]]]¶

    Type: str or type

    __annotations__ = {'added_in': ForwardRef('NotRequired[str]', module='djblets.webapi.resources.base'), 'choices': ForwardRef('Sequence[str]', module='djblets.webapi.resources.base'), 'deprecated_in': ForwardRef('NotRequired[str]', module='djblets.webapi.resources.base'), 'description': ForwardRef('str', module='djblets.webapi.resources.base'), 'items': ForwardRef('NotRequired[ListFieldTypeItemsInfo]', module='djblets.webapi.resources.base'), 'resource': ForwardRef('NotRequired[Union[str, Type[WebAPIResource]]]', module='djblets.webapi.resources.base'), 'type': ForwardRef('Union[Type[BaseAPIFieldType], Type[bytes], Type[str], Type[bool], Type[int], Sequence[str]]', module='djblets.webapi.resources.base')}¶
    __optional_keys__ = frozenset({})¶
    __orig_bases__ = (<function TypedDict>,)¶
    __required_keys__ = frozenset({'added_in', 'choices', 'deprecated_in', 'description', 'items', 'resource', 'type'})¶
    __total__ = True¶
    class AllowedMimetypeEntry[source]¶

    Bases: TypedDict

    An allowed mimetype for an item and list resource.

    New in version 4.0.

    item: Optional[str]¶

    An allowed mimetype for a list resource.

    This can be None or omitted in order to avoid defining a list mimetype for this entry.

    Type:

    str

    __annotations__ = {'item': ForwardRef('NotRequired[Optional[str]]', module='djblets.webapi.resources.base'), 'list': ForwardRef('NotRequired[Optional[str]]', module='djblets.webapi.resources.base')}¶
    __optional_keys__ = frozenset({})¶
    __orig_bases__ = (<function TypedDict>,)¶
    __required_keys__ = frozenset({'item', 'list'})¶
    __total__ = True¶
    class WebAPIResource[source]¶

    Bases: object

    A resource handling HTTP operations for part of the API.

    A WebAPIResource is a RESTful resource living at a specific URL. It can represent either an object or a list of objects, and can respond to various HTTP methods (GET, POST, PUT, DELETE).

    Subclasses are expected to override functions and variables in order to provide specific functionality, such as modifying the resource or creating a new resource.

    For information on writing an API resource, see Writing Web API Resources.

    model: Optional[Type[Model]] = None¶

    A Django model backing this API resource.

    If provided, this resource will automatically handle querying and representation of resource instances. Subclasses will still want to handle access control, fields, parent resources, child resources, and custom-build support for adding, updating, and deleting resources.

    Type:

    type

    fields: Mapping[str, Union[WebAPIResourceFieldInfo, Mapping[str, Any]]] = {}¶

    A mapping of field names to definitions for any serialized objects.

    Each key should be a field name either present in model or defined as a serialize_<fieldname>_field method.

    Type:

    dict

    uri_object_key_regex: str = '[0-9]+'¶

    A regex for mapping keys for an object in an item resource.

    By default, this matches integers. Subclasses can override this to match IDs with other values.

    Type:

    str

    uri_object_key: Optional[str] = None¶

    The key to populate with the ID of an object in an item resource.

    Type:

    str

    model_object_key: str = 'pk'¶

    The key on the provided model for matching an object key.

    This is used when model is set, allowing API resources to automatically query for a model instance matching this model key to the value in the URL corresponding to uri_object_key.

    Type:

    str

    model_parent_key: Optional[str] = None¶

    A key on the provided model for matching a parent resource’s model.

    This is used when model is set, allowing API resources to locate the parent resource for the purposes of access checks and URL generation.

    Type:

    str

    last_modified_field: Optional[str] = None¶

    The field on an item resource object to use for a Last-Modified header.

    Type:

    str

    etag_field: Optional[str] = None¶

    The field on an item resource object to use for an ETag header.

    Type:

    str

    autogenerate_etags: bool = False¶

    Whether to auto-generate ETags for responses.

    If set, and an ETag is not otherwise provided, one will be generated based on the response payload.

    Type:

    bool

    singleton: bool = False¶

    Whether the resource is a singleton.

    Singleton resources behave like an item resource without a parent list resource. They have a single endpoint.

    Type:

    bool

    list_child_resources: Sequence[WebAPIResource] = []¶

    A list of child resources to link to on the list resource.

    Type:

    list of WebAPIResource

    item_child_resources: Sequence[WebAPIResource] = []¶

    A list of child resources to link to on the item resource.

    Type:

    list of WebAPIResource

    allowed_methods: Sequence[str] = ('GET',)¶

    A list of HTTP methods that are allowed on this resource.

    Subclasses must have resource handlers defined for each allowed HTTP method.

    Type:

    tuple of str

    mimetype_vendor: Optional[str] = None¶

    A vendor name to use within item and list resource mimetypes.

    This will be the vendor in category/vnd.vendor.name+format.

    Type:

    str

    mimetype_list_resource_name: Optional[str] = None¶

    An explicit name to use within list resource mimetypees.

    This will be the name in category/vnd.vendor.name+format.

    Type:

    str

    mimetype_item_resource_name: Optional[str] = None¶

    An explicit name to use within item resource mimetypees.

    This will be the name in category/vnd.vendor.name+format.

    Type:

    str

    paginated_cls¶

    The class to use for paginated results in list resources.

    Type:

    list

    alias of WebAPIResponsePaginated

    method_mapping: Mapping[str, str] = {'DELETE': 'delete', 'GET': 'get', 'POST': 'post', 'PUT': 'put'}¶

    A mapping of HTTP methods to handler method names.

    Type:

    dict

    is_webapi_handler: Final[bool] = True¶

    A flag noting this class is an API handler.

    This is always True. It’s set to help middleware or other processors differentiate API views from others.

    Type:

    bool

    __init__() → None[source]¶

    Initialize the API resource.

    This will register the resource and set up state required for processing API requests.

    allowed_mimetypes: Sequence[AllowedMimetypeEntry] = [{'list': 'application/json', 'item': 'application/json'}, {'list': 'application/xml', 'item': 'application/xml'}]¶

    Mimetypes allowed for requests to the resource.

    Each entry defines optional item and/or list mimetypes that correspond to Accept header values.

    Instances of this resource may have a modified version of the list set on the class.

    Type:

    list

    __call__(request: HttpRequest, *args, api_format: Optional[str] = None, **kwargs) → HttpResponseBase[source]¶

    Invoke the correct HTTP handler based on the type of request.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • api_format (str, optional) –

      The API format requested by the caller (json or xml).

      This is considered legacy and may be removed in a future release.

    • *args (tuple) – Additional positional arguments passed by the URL dispatcher.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The resulting HTTP response from the API handler.

    Return type:

    django.http.HttpResponseBase

    __name__ = 'WebAPIResource'[source]¶
    name[source]¶

    The name of the resource, used for keys in the payloads.

    If model is set, this will be the lowercase version of the model name. Otherwise, it will be the lowercase version of this resource class’s name.

    Subclasses can override this to set an explicit name.

    Type:

    str

    name_plural[source]¶

    The plural name of the object, used for lists.

    If singleton is set, this will be the result of name. Otherwise, it will be pluralized form of name.

    Subclasses can override this to set an explicit plural name.

    Type:

    str

    property item_result_key: str[source]¶

    The key for serialized objects in an item payload.

    This defaults to using name as the key. Subclasses can override this to set an explicit key.

    Type:

    str

    property list_result_key: str[source]¶

    The key for serialized object lists in a list payload.

    This defaults to using name_plural as the key. Subclasses can override this to set an explicit key.

    Type:

    str

    uri_name[source]¶

    The name of the resource in the URI.

    This can be overridden when the name in the URI needs to differ from the name used for the resource.

    Type:

    str

    property link_name: str[source]¶

    The name of the resource for use in a link.

    This can be overridden when the name in the link needs to differ from the name used for the resource.

    Type:

    str

    uri_template_name[source]¶

    The name of the resource for use in URI templates.

    This will be used as the key for this resource in djblets.webapi.resource.root.RootResource’s list of URI templates. This can be overridden when the URI template name for this resource needs to differ from the name used for the resource.

    This must be unique to the resource. If set to None this resource will be excluded from the URI templates list.

    New in version 3.1.0.

    Type:

    str or None

    uri_template_name_plural[source]¶

    The plural name of the resource for use in URI templates.

    This will be used as the key for the list version of this resource in djblets.webapi.resource.root.RootResource’s list of URI templates. This can be overridden when the URI template name for this resource needs to differ from the name used for the resource.

    This must be unique to the resource. If set to None the list version of this resource will be excluded from the URI templates list.

    New in version 3.1.0.

    Type:

    str or None

    call_method_view(request: HttpRequest, method: str, view: Callable, *args, **kwargs) → WebAPIResourceHandlerResult[source]¶

    Call the given HTTP method handler view.

    This will just call the given view by default, passing in all args and kwargs.

    This can be overridden by subclasses to perform additional checks or pass additional data to the view.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • method (str) – The HTTP method used in the request.

    • view (callable) – The API handler function to call for the HTTP method.

    • *args (tuple) – Positional arguments to pass to the view.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    build_response_args(request: HttpRequest) → KwargsDict[source]¶

    Build keyword arguments to pass to a response class.

    Parameters:

    request (django.http.HttpRequest) – The HTTP request from the client.

    Returns:

    Keyword arguments to pass to the response class.

    Return type:

    dict

    get_object(request: HttpRequest, id_field: Optional[str] = None, *args, **kwargs) → Any[source]¶

    Return an object, given the captured parameters from a URL.

    This will perform a query for the object, taking into account model_object_key, uri_object_key, and any captured parameters from the URL.

    This requires that model and uri_object_key` are set.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • id_field (str, optional) –

      An explicit ID field on the object.

      If not provided, this will default to model_object_key.

    • *args (tuple) – Positional arguments passed to the API handler method.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Raises:

    django.core.exceptions.ObjectDoesNotExist – The object does not exist in the database.

    post(request: HttpRequest, *args, api_format: Optional[str], **kwargs) → WebAPIResourceHandlerResult[source]¶

    Handle HTTP POST requests.

    This is not meant to be overridden unless there are specific needs.

    This will invoke create() if doing an HTTP POST on a list resource.

    By default, an HTTP POST is not allowed on individual object resources.

    Parameters:
    • request (django.http.HttpClient) – The HTTP client from the request.

    • *args (tuple) – Positional arguments passed to the view.

    • api_format (str) – An explicit API format requested for the response.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The HTTP response, API error, or tuple results from the API handler.

    Return type:

    WebAPIResourceHandlerResult

    put(request: HttpRequest, *args, api_format: Optional[str], **kwargs) → WebAPIResourceHandlerResult[source]¶

    Handle HTTP PUT requests.

    This is not meant to be overridden unless there are specific needs.

    This will invoke update() if doing an HTTP PUT.

    Parameters:
    • request (django.http.HttpClient) – The HTTP client from the request.

    • *args (tuple) – Positional arguments passed to the view.

    • api_format (str) – An explicit API format requested for the response.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The HTTP response, API error, or tuple results from the API handler.

    Return type:

    WebAPIResourceHandlerResult

    get(**kwargs)[source]¶

    Handle HTTP GETs to item resources.

    By default, this will check for access permissions and query for the object. It will then return a serialized form of the object.

    This may need to be overridden if needing more complex logic.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple) – Positional arguments passed to the view.

    • api_format (str) – An explicit API format requested for the response.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The HTTP response, API error, or tuple results from the API handler.

    Return type:

    WebAPIResourceHandlerResult

    get_list(**kwargs)[source]¶

    Handle HTTP GETs to list resources.

    By default, this will query for a list of objects and return the list in a serialized form.

    This may need to be overridden if needing more complex logic.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple) – Positional arguments passed to the view.

    • api_format (str) – An explicit API format requested for the response.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The HTTP response, API error, or tuple results from the API handler.

    Return type:

    WebAPIResourceHandlerResult

    create(**kwargs)[source]¶

    Handle HTTP POST requests to list resources.

    This is used to create a new object on the list, given the data provided in the request. It should usually return HTTP 201 Created upon success.

    By default, this returns HTTP 405 Method Not Allowed.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple) – Positional arguments passed to the view.

    • api_format (str) – An explicit API format requested for the response.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The HTTP response, API error, or tuple results from the API handler.

    Return type:

    WebAPIResourceHandlerResult

    update(**kwargs)[source]¶

    Handle HTTP PUT requests to object resources.

    This is used to update an object, given full or partial data provided in the request. It should usually return HTTP 200 OK upon success.

    By default, this returns HTTP 405 Method Not Allowed.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple) – Positional arguments passed to the view.

    • api_format (str) – An explicit API format requested for the response.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The HTTP response, API error, or tuple results from the API handler.

    Return type:

    WebAPIResourceHandlerResult

    delete(**kwargs)[source]¶

    Handles HTTP DELETE requests to object resources.

    This is used to delete an object, if the user has permissions to do so.

    By default, this deletes the object and returns HTTP 204 No Content.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple) – Positional arguments passed to the view.

    • api_format (str) – An explicit API format requested for the response.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The HTTP response, API error, or tuple results from the API handler.

    Return type:

    WebAPIResourceHandlerResult

    get_queryset(request: Optional[HttpRequest], is_list: bool = False, *args, **kwargs) → QuerySet[source]¶

    Return a queryset used for querying objects or lists of objects.

    Subclasses can override this to filter objects, include related objects, or otherwise specialize the queryset.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • is_list (bool, optional) –

      Whether this should be returning a queryset for a list resource.

      Subclasses can use this to query additional state based on query arguments or other criteria.

    • *args (tuple) – Positional arguments passed to the view.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    A queryset for objects for this resource.

    Return type:

    django.db.models.QuerySet

    Raises:

    django.core.exceptions.ObjectDoesNotExist – The object does not exist. This may be thrown by an overridden function if the object or a parent object does not exist.

    get_url_patterns() → List[Union[URLPattern, URLResolver]][source]¶

    Return the Django URL patterns for this object and its children.

    This is used to automatically build up the URL hierarchy for all objects. Projects should call this for top-level resources and return them in the urls.py files.

    Returns:

    The list of URL patterns.

    Return type:

    list

    has_access_permissions(request: HttpRequest, obj: Any, *args, **kwargs) → bool[source]¶

    Return whether the user has read access to the item resource.

    This is used for HTTP GET requests on the item resource. For list resources, see has_list_access_permissions().

    Subclasses should override this to provide any specific access control needed for accessing items.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • obj (object) – The object to check for permissions.

    • *args (tuple) – Additional positional arguments passed to the view.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    True if the user has access permissions. False if it does not.

    Return type:

    bool

    has_list_access_permissions(request: HttpRequest, *args, **kwargs) → bool[source]¶

    Return whether the user has read access to the list resource.

    This is used for HTTP GET requests on the list resource. For item resources, see has_access_permissions().

    By default, this will check the parent resource (if there is one) for access permissions.

    Subclasses should override this to provide any specific access control needed for accessing lists of items.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple) – Additional positional arguments passed to the view.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    True if the user has access permissions. False if it does not.

    Return type:

    bool

    has_modify_permissions(request: HttpRequest, obj: Any, *args, **kwargs) → bool[source]¶

    Return whether the user can modify the object.

    This is used for HTTP PUT requests on the item resource.

    Subclasses should override this to provide any specific access control needed for modifying items.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • obj (object) – The object to check for permissions.

    • *args (tuple) – Additional positional arguments passed to the view.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    True if the user has modify permissions. False if it does not.

    Return type:

    bool

    has_delete_permissions(request: HttpRequest, obj: Any, *args, **kwargs) → bool[source]¶

    Return whether the user can delete this object.

    This is used for HTTP DELETE requests on the list resource.

    Subclasses should override this to provide any specific access control needed for deleting items.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • obj (object) – The object to check for permissions.

    • *args (tuple) – Additional positional arguments passed to the view.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    True if the user has delete permissions. False if it does not.

    Return type:

    bool

    get_link_serializer(field: str) → _SerializeLinkFunc[source]¶

    Return the function to use for serializing a link field.

    This will first look for a function named serialize_field_link on the resource. If not available or not callable, serialize_link will be returned.

    Parameters:

    field (str) – The field in the resource for which to generate a link.

    Returns:

    The link serializer function.

    Return type:

    callable

    serialize_link(obj: Any, request: Optional[HttpRequest], *args, **kwargs) → WebAPIResponseLink[source]¶

    Return a serialized dictionary for a link.

    This will find the resource serializer for a given object and return a dictionary containing information on the link.

    Parameters:
    • obj (object) – The object being linked to.

    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple) – Positional arguments passed to the view.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The serialized link information.

    Return type:

    dict

    get_object_title(obj: Any, request: Optional[HttpRequest] = None, *args, **kwargs) → str[source]¶

    Return an object’s title.

    This is called when generating a link to an object’s resource.

    By default, this returns the object’s string representation. Subclasses can override this to return a different title.

    Parameters:
    • obj (object) – The object for which to generate a title.

    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple) – Additional positional arguments.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The object’s title.

    Return type:

    str

    serialize_object(obj: Any, request: Optional[HttpRequest] = None, *args, **kwargs) → WebAPIResponsePayload[source]¶

    Return a serialized representation of an object.

    This will generate a dictionary containing information on an object, based on the API resource serializer registered for the object type.

    By default, the result will contain each field specified in fields, and any links to related resources in a links key.

    This also takes care of expanding any links into object payloads in the list of fields when passing a field name to ?expand= (for HTTP GET) or expand= in the body (for POST or PUT).

    Parameters:
    • obj (object) – The object to serialize.

    • *args (tuple) – Positional arguments passed to the view.

    • request (django.http.HttpRequest, optional) –

      The HTTP request from the client.

      This can be None.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The serialized object payload.

    Return type:

    dict

    get_only_fields(request: Optional[HttpRequest]) → Optional[List[str]][source]¶

    Return the list of the only fields that the payload should include.

    If the user has requested that no fields should be provided, this will return an empty list.

    If all fields will be included in the payload, this will return None.

    Parameters:

    request (django.http.HttpRequest) – The HTTP request from the client.

    Returns:

    The list of fields, an empty list, or None.

    Return type:

    list of str

    get_only_links(request: Optional[HttpRequest]) → Optional[List[str]][source]¶

    Return the list of the only links that the payload should include.

    If the user has requested that no links should be provided, this will return an empty list.

    If all links will be included in the payload, this will return None.

    Parameters:

    request (django.http.HttpRequest) – The HTTP request from the client.

    Returns:

    The list of links, an empty list, or None.

    Return type:

    list of str

    get_serializer_for_object(obj: Any) → Optional[WebAPIResource][source]¶

    Return the serializer used to serialize an object.

    This is called when serializing objects for payloads returned by this resource instance. It must return the resource instance that will be responsible for serializing the given object for the payload.

    By default, this calls djblets.webapi.resources.registry. get_resource_for_object() to find the appropriate resource.

    Parameters:

    obj (object) – The object to serialize.

    Returns:

    The resource handling serialization, or None if not found.

    Return type:

    WebAPIResource

    get_links(resources: Sequence[WebAPIResource] = [], obj: Optional[Any] = None, *args, request: Optional[HttpRequest] = None, **kwargs) → WebAPIResponseLinks[source]¶

    Return a dictionary of links coming off this resource.

    The resulting links will point to the resources passed in resources, and will also provide special resources for self (which points back to the official location for this resource) and one per HTTP method/operation allowed on this resource.

    Parameters:
    • resources (list of WebAPIResource, optional) – A list of resources for which to generate additional links.

    • obj (object, optional) – The object being serialized, for use as a base for resource URLs.

    • *args (tuple) – Additional positional arguments passed to the view.

    • request (django.http.HttpRequest) – The HTTP request from the client.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    A dictionary of link names to link information.

    Return type:

    dict

    get_related_links(obj: Optional[Any] = None, request: Optional[HttpRequest] = None, *args, **kwargs) → WebAPIResponseLinks[source]¶

    Return links related to this resource.

    The result should be a dictionary of link names to a dictionary of information. See djblets.webapi.responses.WebAPIResponseLink for the available keys for each link.

    Parameters:
    • obj (object, optional) – The object that the resources will be related to.

    • request (django.http.HttpRequest, optional) – The HTTP request from the client.

    • *args (tuple) – Positional arguments passed to the view.

    • **kwargs (tuple) – Keyword arguments representing values captured from the URL.

    Returns:

    The dictionary of related links.

    Return type:

    djblets.webapi.responses.WebAPIResponseLinks

    get_href(obj: Any, request: Optional[HttpRequest], *args, **kwargs) → Optional[str][source]¶

    Return the absolute URL for an object.

    This will attempt to build a URL that points to the object’s item resource.

    If uri_object_key is set, this will call get_item_url(), passing the model’s key (defined as model_object_key) as uri_object_key, along with any parent IDs returned from get_href_parent_ids().

    Parameters:
    • obj (object) – The object being linked to.

    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple) – Positional arguments passed to the view.

    • **kwargs (dict) –

      Keyword arguments representing values captured from the URL.

      These will be passed to get_href_parent_ids().

    Returns:

    The resulting URL to the object, or None if it could not be generated.

    Return type:

    str

    get_list_url(**kwargs) → str[source]¶

    Return the absolute URL to the list version of this resource.

    This will generate a URL for the list resource, given the provided arguments for the URL pattern.

    By default, this calls build_resource_url() with name_plural and the provided keyword arguments.

    Parameters:

    **kwargs (dict) –

    Keyword arguments representing values captured from the URL.

    These will be passed to build_resource_url().

    Returns:

    The resulting absolute URL to the list resource.

    Return type:

    str

    get_item_url(**kwargs) → str[source]¶

    Return the absolute URL to the item version of this resource.

    This will generate a URL for the item resource, given the provided arguments for the URL pattern.

    By default, this calls build_resource_url() with name and the provided keyword arguments.

    Parameters:

    **kwargs (dict) –

    Keyword arguments representing values captured from the URL.

    These will be passed to build_resource_url().

    Returns:

    The resulting absolute URL to the item resource.

    Return type:

    str

    build_resource_url(name: str, request: Optional[HttpRequest] = None, **kwargs) → str[source]¶

    Build a resource URL for the given name and keyword arguments.

    This can be overridden by subclasses that have special requirements for URL resolution.

    Parameters:
    • name (str) – The name of the resource.

    • request (django.http.HttpRequest) – The HTTP request from the client.

    • **kwargs (dict) –

      Keyword arguments representing values captured from the URL.

      These will be passed to _build_named_url().

    Returns:

    The resulting absolute URL to the resource.

    Return type:

    str

    get_href_parent_ids(obj: Any, **kwargs) → Dict[str, str][source]¶

    Return a dictionary mapping parent object keys to object values.

    This will walk up the resource tree and return a mapping of parent URI object keys to values in the object instances. These are meant to be used to generate a full URL back to this resource.

    Each parent object’s resource class will be used to handle that level of the tree. The resource’s model_parent_key must be provided in order to process that level or higher in the tree.

    Parameters:
    • obj (object) – The object for which to return parent IDs.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    A mapping of object IDs to values.

    Return type:

    dict

    get_parent_object(obj: Any) → Optional[Any][source]¶

    Return the parent of an object.

    By default, this uses model_parent_key to figure out the parent.

    Subclasses can override this for more complex behavior.

    Parameters:

    obj (object) – The object for which to return a parent.

    Returns:

    The parent object, or None if not found.

    Return type:

    object

    get_last_modified(request: HttpRequest, obj: Any) → Optional[datetime][source]¶

    Return the last-modified timestamp of an object.

    By default, this uses last_modified_field to determine what field in the model represents the last-modified timestamp of the object.

    Subclasses can override this for more complex behavior.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • obj (object) – The object for which to return a last-modified timestamp.

    Returns:

    The last-modified timestamp, or None if not found.

    Return type:

    datetime.datetime

    get_etag(request: HttpRequest, obj: Any, *args, **kwargs) → Optional[str][source]¶

    Return the ETag representing the state of the object.

    By default, this uses etag_field to determine what field in the model is unique enough to represent the state of the object.

    Subclasses can override this for more complex behavior. Any overridden functions should make sure to pass the result through encode_etag() before returning a value.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • obj (object) – The object for which to return an ETag.

    • *args (tuple) – Additional positional arguments passed to the view.

    • **kwargs (dict) – Keyword arguments representing values captured from the URL.

    Returns:

    The resulting encoded ETag, or None if one could not be generated.

    Return type:

    str

    encode_etag(request: HttpRequest, etag: str, *args, **kwargs) → str[source]¶

    Return an encoded ETag for usage in a header.

    This will take a precomputed ETag, augment it with additional information, encode it as a SHA1, and return it.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • etag (str) – The ETag to encode.

    • *args (tuple, unused) – Additional positional arguments passed to the view.

    • **kwargs (dict, unused) – Keyword arguments representing values captured from the URL.

    Returns:

    The encoded ETag.

    Return type:

    str

    are_cache_headers_current(request: HttpRequest, last_modified: Optional[datetime] = None, etag: Optional[str] = None) → bool[source]¶

    Return whether cache headers from the client are current.

    This will compare the optionally-provided timestamp and ETag against any conditional cache headers sent by the client to determine if the headers are current. If they are, the caller can return HttpResponseNotModified instead of a payload.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • last_modified (datetime.datetime, optional) – The current last-modified timestamp for the object, if available.

    • etag (str, optional) – The current ETag for the payload, if available.

    Returns:

    True if the client’s cache headers represent a current version of the resource payload. False if they do not.

    Return type:

    bool

    get_no_access_error(request: HttpRequest, *args, **kwargs) → WebAPIError[source]¶

    Return an appropriate error when access is denied.

    By default, this will return PERMISSION_DENIED if the user is logged in, and NOT_LOGGED_IN if the user is anonymous.

    Subclasses can override this to return different or more detailed errors.

    Parameters:
    • request (django.http.HttpRequest) – The HTTP request from the client.

    • *args (tuple, unused) – Additional positional arguments passed to the view.

    • **kwargs (dict, unused) – Keyword arguments representing values captured from the URL.

    Returns:

    The API error to send to the client.

    Return type:

    djblets.webapi.errors.WebAPIError

    __annotations__ = {'_parent_resource': 'Optional[WebAPIResource]', '_prefetch_related_fields': 'List[str]', '_select_related_fields': 'List[str]', 'allowed_methods': 'Sequence[str]', 'allowed_mimetypes': 'Sequence[AllowedMimetypeEntry]', 'autogenerate_etags': 'bool', 'etag_field': 'Optional[str]', 'fields': 'Mapping[str, Union[WebAPIResourceFieldInfo, Mapping[str, Any]]]', 'is_webapi_handler': 'Final[bool]', 'item_child_resources': 'Sequence[WebAPIResource]', 'last_modified_field': 'Optional[str]', 'list_child_resources': 'Sequence[WebAPIResource]', 'method_mapping': 'Mapping[str, str]', 'mimetype_item_resource_name': 'Optional[str]', 'mimetype_list_resource_name': 'Optional[str]', 'mimetype_vendor': 'Optional[str]', 'model': 'Optional[Type[Model]]', 'model_object_key': 'str', 'model_parent_key': 'Optional[str]', 'paginated_cls': 'Type[WebAPIResponsePaginated]', 'singleton': 'bool', 'uri_object_key': 'Optional[str]', 'uri_object_key_regex': 'str'}¶

    Keep up with the latest Review Board releases, security updates, and helpful information.

    About
    News
    Demo
    RBCommons Hosting
    Integrations
    Happy Users
    Support Options
    Documentation
    FAQ
    User Manual
    RBTools
    Administration Guide
    Power Pack
    Release Notes
    Downloads
    Review Board
    RBTools
    Djblets
    Power Pack
    Package Store
    PGP Signatures
    Contributing
    Bug Tracker
    Submit Patches
    Development Setup
    Wiki
    Follow Us
    Mailing Lists
    Reddit
    Twitter
    Mastodon
    Facebook
    YouTube

    Copyright © 2006-2025 Beanbag, Inc. All rights reserved.

    Terms of Service — Privacy Policy — AI Ethics Policy — Branding

    On this page

    • [Top]
    • WebAPIResourceHandlerResult
    • WebAPIResourceFieldInfo
      • WebAPIResourceFieldInfo.description
      • WebAPIResourceFieldInfo.type
      • WebAPIResourceFieldInfo.added_in
      • WebAPIResourceFieldInfo.choices
      • WebAPIResourceFieldInfo.deprecated_in
      • WebAPIResourceFieldInfo.resource
      • WebAPIResourceFieldInfo.__annotations__
      • WebAPIResourceFieldInfo.__optional_keys__
      • WebAPIResourceFieldInfo.__orig_bases__
      • WebAPIResourceFieldInfo.__required_keys__
      • WebAPIResourceFieldInfo.__total__
    • AllowedMimetypeEntry
      • AllowedMimetypeEntry.item
      • AllowedMimetypeEntry.__annotations__
      • AllowedMimetypeEntry.__optional_keys__
      • AllowedMimetypeEntry.__orig_bases__
      • AllowedMimetypeEntry.__required_keys__
      • AllowedMimetypeEntry.__total__
    • WebAPIResource
      • WebAPIResource.model
      • WebAPIResource.fields
      • WebAPIResource.uri_object_key_regex
      • WebAPIResource.uri_object_key
      • WebAPIResource.model_object_key
      • WebAPIResource.model_parent_key
      • WebAPIResource.last_modified_field
      • WebAPIResource.etag_field
      • WebAPIResource.autogenerate_etags
      • WebAPIResource.singleton
      • WebAPIResource.list_child_resources
      • WebAPIResource.item_child_resources
      • WebAPIResource.allowed_methods
      • WebAPIResource.mimetype_vendor
      • WebAPIResource.mimetype_list_resource_name
      • WebAPIResource.mimetype_item_resource_name
      • WebAPIResource.paginated_cls
      • WebAPIResource.method_mapping
      • WebAPIResource.is_webapi_handler
      • WebAPIResource.__init__()
      • WebAPIResource.allowed_mimetypes
      • WebAPIResource.__call__()
      • WebAPIResource.__name__
      • WebAPIResource.name
      • WebAPIResource.name_plural
      • WebAPIResource.item_result_key
      • WebAPIResource.list_result_key
      • WebAPIResource.uri_name
      • WebAPIResource.link_name
      • WebAPIResource.uri_template_name
      • WebAPIResource.uri_template_name_plural
      • WebAPIResource.call_method_view()
      • WebAPIResource.build_response_args()
      • WebAPIResource.get_object()
      • WebAPIResource.post()
      • WebAPIResource.put()
      • WebAPIResource.get()
      • WebAPIResource.get_list()
      • WebAPIResource.create()
      • WebAPIResource.update()
      • WebAPIResource.delete()
      • WebAPIResource.get_queryset()
      • WebAPIResource.get_url_patterns()
      • WebAPIResource.has_access_permissions()
      • WebAPIResource.has_list_access_permissions()
      • WebAPIResource.has_modify_permissions()
      • WebAPIResource.has_delete_permissions()
      • WebAPIResource.get_link_serializer()
      • WebAPIResource.serialize_link()
      • WebAPIResource.get_object_title()
      • WebAPIResource.serialize_object()
      • WebAPIResource.get_only_fields()
      • WebAPIResource.get_only_links()
      • WebAPIResource.get_serializer_for_object()
      • WebAPIResource.get_links()
      • WebAPIResource.get_related_links()
      • WebAPIResource.get_href()
      • WebAPIResource.get_list_url()
      • WebAPIResource.get_item_url()
      • WebAPIResource.build_resource_url()
      • WebAPIResource.get_href_parent_ids()
      • WebAPIResource.get_parent_object()
      • WebAPIResource.get_last_modified()
      • WebAPIResource.get_etag()
      • WebAPIResource.encode_etag()
      • WebAPIResource.are_cache_headers_current()
      • WebAPIResource.get_no_access_error()
      • WebAPIResource.__annotations__