Batch Requests
Batch requests allow you to combine multiple API calls into a single HTTP request, improving performance and reducing API quota usage.
Why Use Batch Requests?
- Performance - Reduce network overhead
- Efficiency - Lower API quota consumption
- Atomicity - Execute related operations together
Basic Usage
Using BatchRequestManager
pythonfrom gspace.utils.batch_requests import BatchRequestManager, BatchRequest # Initialize batch manager batch = BatchRequestManager() # Add multiple requests batch.add_request( BatchRequest( service=calendar.service, method='events().list', parameters={'calendarId': 'primary'} ) ) batch.add_request( BatchRequest( service=gmail.service, method='messages().list', parameters={'userId': 'me'} ) ) # Execute all requests responses = batch.execute() for response in responses: if response.is_success(): print(response.data) else: print(f"Error: {response.error}")
Batch Request Types
Calendar Batch Operations
python# Batch create multiple events requests = [] for event_data in events_data: requests.append( BatchRequest( service=calendar.service, method='events().insert', parameters={ 'calendarId': 'primary', 'body': event_data } ) ) batch = BatchRequestManager() for req in requests: batch.add_request(req) results = batch.execute()
Drive Batch Operations
python# Batch get file metadata file_ids = ['id1', 'id2', 'id3'] batch = BatchRequestManager() for file_id in file_ids: batch.add_request( BatchRequest( service=drive.service, method='files().get', parameters={'fileId': file_id} ) ) results = batch.execute()
Best Practices
- Limit batch size - Google APIs have limits (typically 100 requests per batch)
- Group related requests - Batch operations that logically belong together
- Handle errors - Check each response for success/failure
- Retry failed requests - Implement retry logic for failed batch items
Error Handling
pythonresponses = batch.execute() for i, response in enumerate(responses): if response.is_success(): # Process successful response process_data(response.data) else: # Handle error error = response.error if error.status_code == 429: # Rate limit # Retry after delay retry_request(batch.requests[i]) else: # Log and handle other errors logger.error(f"Request failed: {error}")
Limitations
- Maximum 100 requests per batch
- All requests must use the same authentication
- Some operations cannot be batched
- Response size limits apply