🔍 Code Extractor

class ODataV4BatchRequest

Maturity: 48

A class that handles OData V4 JSON batch requests, allowing multiple OData operations to be bundled and executed in a single HTTP request.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/odata/v4/batch_request.py
Lines:
11 - 86
Complexity:
moderate

Purpose

ODataV4BatchRequest extends ODataRequest to provide specialized functionality for creating, sending, and processing OData V4 batch requests in JSON format. It serializes multiple queries into a single batch payload, sends them to the server, and then parses the batch response to extract individual query results. This is useful for optimizing network traffic by combining multiple API calls into one request.

Source Code

class ODataV4BatchRequest(ODataRequest):
    """JSON batch request"""

    def build_request(self, query):
        """
        Builds a batch request

        :type query: office365.runtime.queries.batch.BatchQuery
        """
        request = RequestOptions(query.url)
        request.method = HttpMethod.Post
        request.ensure_header("Content-Type", "application/json")
        request.ensure_header("Accept", "application/json")
        request.data = self._prepare_payload(query)
        return request

    def process_response(self, response, query):
        """Parses an HTTP response.

        :type response: requests.Response
        :type query: office365.runtime.queries.batch.BatchQuery
        """
        for sub_qry, sub_resp in self._extract_response(response, query):
            sub_resp.raise_for_status()
            super(ODataV4BatchRequest, self).process_response(sub_resp, sub_qry)

    @staticmethod
    def _extract_response(response, query):
        """
        :type response: requests.Response
        :type query: office365.runtime.queries.batch.BatchQuery
        """
        json_responses = response.json()
        for json_resp in json_responses["responses"]:
            resp = requests.Response()
            resp.status_code = int(json_resp["status"])
            resp.headers = CaseInsensitiveDict(json_resp["headers"])
            resp._content = json.dumps(json_resp["body"]).encode("utf-8")
            qry_id = int(json_resp["id"])
            qry = query.ordered_queries[qry_id]
            yield qry, resp

    def _prepare_payload(self, query):
        """
        Serializes a batch request body.

        :type query: office365.runtime.queries.batch.BatchQuery
        """
        requests_json = []
        for qry in query.queries:
            qry_id = str(len(requests_json))
            requests_json.append(self._normalize_request(qry, qry_id))

        return {"requests": requests_json}

    @staticmethod
    def _normalize_request(query, query_id, depends_on=None):
        """
        :type query: office365.runtime.queries.client_query.ClientQuery
        :type query_id: str
        :type depends_on:  list[str] or None
        """
        request = query.build_request()
        allowed_props = ["id", "method", "headers", "url", "body"]
        request_json = dict(
            (k, v)
            for k, v in vars(request).items()
            if v is not None and k in allowed_props
        )
        request_json["id"] = query_id
        if depends_on is not None:
            request_json["dependsOn"] = depends_on
        request_json["url"] = request_json["url"].replace(
            query.context.service_root_url(), ""
        )
        return request_json

Parameters

Name Type Default Kind
bases ODataRequest -

Parameter Details

bases: Inherits from ODataRequest, which provides base functionality for OData request handling. The class does not define an explicit __init__ method, so it uses the parent class constructor.

Return Value

Instantiation returns an ODataV4BatchRequest object. The build_request method returns a RequestOptions object configured for batch requests. The process_response method has no return value but processes responses in-place. The _extract_response method yields tuples of (query, response) pairs. The _prepare_payload method returns a dictionary with batch request structure. The _normalize_request method returns a dictionary representing a normalized request.

Class Interface

Methods

build_request(self, query) -> RequestOptions

Purpose: Constructs an HTTP request object for a batch operation by serializing multiple queries into a JSON batch payload

Parameters:

  • query: A BatchQuery object containing multiple queries to be executed in a single batch request

Returns: A RequestOptions object configured with POST method, JSON content-type headers, and the serialized batch payload

process_response(self, response, query) -> None

Purpose: Parses the batch HTTP response and processes each individual sub-response, delegating to the parent class for actual response handling

Parameters:

  • response: A requests.Response object containing the batch response from the server
  • query: The BatchQuery object that was used to build the original request

Returns: None. Processes responses in-place and may raise exceptions for failed sub-requests

_extract_response(response, query) -> Iterator[Tuple[ClientQuery, requests.Response]] static

Purpose: Extracts individual query responses from the batch response JSON and reconstructs them as separate Response objects

Parameters:

  • response: A requests.Response object containing the JSON batch response
  • query: The BatchQuery object containing the ordered list of queries

Returns: A generator yielding tuples of (query, response) pairs, where each response is a reconstructed requests.Response object

_prepare_payload(self, query) -> dict

Purpose: Serializes a BatchQuery into the JSON structure required for OData V4 batch requests

Parameters:

  • query: A BatchQuery object containing the queries to be serialized

Returns: A dictionary with a 'requests' key containing a list of normalized request objects

_normalize_request(query, query_id, depends_on=None) -> dict static

Purpose: Converts a ClientQuery into a normalized dictionary format suitable for inclusion in a batch request, with relative URLs and dependency tracking

Parameters:

  • query: A ClientQuery object to be normalized
  • query_id: A string identifier for this query within the batch
  • depends_on: Optional list of query IDs that this query depends on (for sequential execution)

Returns: A dictionary containing the normalized request with id, method, headers, url (relative), and optionally body and dependsOn fields

Dependencies

  • json
  • requests
  • office365.runtime.http.http_method
  • office365.runtime.http.request_options
  • office365.runtime.odata.request
  • office365.runtime.queries.batch
  • office365.runtime.queries.client_query

Required Imports

import json
import requests
from requests.structures import CaseInsensitiveDict
from office365.runtime.http.http_method import HttpMethod
from office365.runtime.http.request_options import RequestOptions
from office365.runtime.odata.request import ODataRequest

Usage Example

from office365.runtime.odata.v4.batch_request import ODataV4BatchRequest
from office365.runtime.queries.batch import BatchQuery
from office365.runtime.client_runtime_context import ClientRuntimeContext

# Assuming you have a context and queries set up
context = ClientRuntimeContext(service_root_url)
batch_query = BatchQuery(context)

# Add queries to the batch
batch_query.add(query1)
batch_query.add(query2)
batch_query.add(query3)

# Create batch request handler
batch_request = ODataV4BatchRequest()

# Build the request
request_options = batch_request.build_request(batch_query)

# Execute the request (typically done by the context)
response = requests.request(
    method=request_options.method,
    url=request_options.url,
    headers=request_options.headers,
    data=json.dumps(request_options.data)
)

# Process the response
batch_request.process_response(response, batch_query)

Best Practices

  • Always ensure queries are properly added to a BatchQuery object before calling build_request
  • The class processes responses in order, matching them to queries by ID, so query order matters
  • Each sub-query response is validated with raise_for_status(), so handle HTTP errors appropriately
  • The _normalize_request method strips the service root URL from request URLs to create relative paths required by batch format
  • Use this class through the office365 library's context rather than instantiating directly for proper integration
  • Batch requests are limited by server-side constraints on the number of operations per batch
  • All requests in a batch share the same authentication context
  • Failed individual requests within a batch will raise exceptions during process_response

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class ODataBatchV3Request 87.9% similar

    ODataBatchV3Request is a specialized OData request handler for constructing and processing OData v3 batch requests using multipart/mixed HTTP format.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/odata/v3/batch_request.py
  • class ODataRequest 78.0% similar

    ODataRequest is a specialized HTTP request handler for OData protocol operations, extending ClientRequest to build, execute, and process OData-compliant requests with JSON format support.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/odata/request.py
  • class GraphRequest 67.2% similar

    GraphRequest is a specialized OData request class configured for Microsoft Graph API interactions using V4 JSON format.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/graph_request.py
  • class V4JsonFormat 60.6% similar

    V4JsonFormat is a class that implements OData V4 JSON format specifications, managing metadata levels, IEEE754 compatibility, and streaming options for JSON serialization.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/odata/v4/json_format.py
  • class SharePointRequest 59.9% similar

    SharePointRequest is a specialized OData request class configured to use JSON Light format for SharePoint API interactions.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/request.py
← Back to Browse