### Install Bazooka Source: https://github.com/infraguys/bazooka/blob/master/README.md Install the Bazooka library using pip. This is the first step to using the client in your Python projects. ```bash pip install bazooka ``` -------------------------------- ### Build REST API Client with RESTClientMixIn Source: https://context7.com/infraguys/bazooka/llms.txt Example of creating a custom API client by inheriting from `RESTClientMixIn` and `Client`. This mixin provides utilities for constructing URIs. ```python from bazooka.common import RESTClientMixIn, force_last_slash from bazooka.client import Client class MyAPIClient(RESTClientMixIn, Client): def __init__(self, base_url, **kwargs): super().__init__(**kwargs) self._endpoint = base_url def get_user(self, user_id): uri = self._build_resource_uri(['users', user_id]) return self.get(uri) def list_users(self): uri = self._build_collection_uri(['users']) # Ensures trailing slash return self.get(uri) def get_user_posts(self, user_id, post_id=None): paths = ['users', user_id, 'posts'] if post_id: paths.append(post_id) uri = self._build_resource_uri(paths) else: uri = self._build_collection_uri(paths) return self.get(uri) # Usage api = MyAPIClient('http://api.example.com/v1') user = api.get_user(123) # GET http://api.example.com/v1/users/123 users = api.list_users() # GET http://api.example.com/v1/users/ posts = api.get_user_posts(123) # GET http://api.example.com/v1/users/123/posts/ post = api.get_user_posts(123, 5) # GET http://api.example.com/v1/users/123/posts/5 ``` -------------------------------- ### Basic GET Request with Bazooka Source: https://github.com/infraguys/bazooka/blob/master/README.md Perform a basic GET request to a specified URL and print the JSON response. Ensure the 'bazooka' library is imported. ```python import bazooka client = bazooka.Client() print(client.get('http://example.com').json()) ``` -------------------------------- ### HTTP Methods with BasicAuthClient Source: https://context7.com/infraguys/bazooka/llms.txt Make authenticated requests using BasicAuthClient. The client automatically handles adding Basic Authentication headers to GET, POST, and other requests. ```python # All requests will automatically include Basic Auth headers response = client.get('http://api.example.com/protected/resource') data = response.json() ``` ```python # POST to authenticated endpoint response = client.post( 'http://api.example.com/protected/data', json={'key': 'value'} ) ``` -------------------------------- ### Handling HTTP Errors with Bazooka Source: https://github.com/infraguys/bazooka/blob/master/README.md Implement error handling for HTTP requests made with Bazooka. This example specifically catches NotFoundError, ConflictError, and other 4xx errors. ```python import bazooka from bazooka import exceptions client = bazooka.Client() try: response = client.get('http://example.com', timeout=10) except exceptions.NotFoundError: # process 404 error pass except exceptions.ConflictError: # process 409 error pass except exceptions.BaseHTTPException as e: # process other HTTP errors if e.code in range(400, 500): print(f"4xx Error: {e}") else: raise ``` -------------------------------- ### HTTP Methods with Bazooka Client Source: https://context7.com/infraguys/bazooka/llms.txt Perform various HTTP requests using the Bazooka client. Supports GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS methods with options for query parameters, JSON bodies, and form data. ```python # GET request with query parameters response = client.get('http://api.example.com/users', params={'page': 1, 'limit': 10}) ``` ```python # POST request with JSON body response = client.post( 'http://api.example.com/users', json={'name': 'John Doe', 'email': 'john@example.com'} ) ``` ```python # PUT request with form data response = client.put('http://api.example.com/users/1', data={'name': 'Jane Doe'}) ``` ```python # PATCH request response = client.patch('http://api.example.com/users/1', json={'status': 'active'}) ``` ```python # DELETE request response = client.delete('http://api.example.com/users/1') ``` ```python # HEAD request (redirects disabled by default) response = client.head('http://api.example.com/users') ``` ```python # OPTIONS request response = client.options('http://api.example.com/users') ``` -------------------------------- ### Initialize BasicAuthClient Source: https://context7.com/infraguys/bazooka/llms.txt Create a specialized client for HTTP Basic Authentication. Pass username and password directly during initialization. All subsequent requests will include the Basic Auth headers. ```python from bazooka.client import BasicAuthClient # Create a client with basic authentication client = BasicAuthClient( username='api_user', password='secure_password', verify_ssl=True, allow_redirects=True, correlation_id='request-12345', log_duration=True, default_timeout=60 ) ``` -------------------------------- ### Initialize Bazooka Client Source: https://context7.com/infraguys/bazooka/llms.txt Instantiate the main Bazooka Client. By default, it raises exceptions for non-2xx status codes. Configure options like authentication, SSL verification, redirects, correlation IDs, logging, and timeouts. ```python import bazooka # Basic client usage client = bazooka.Client() response = client.get('http://api.example.com/users') print(response.json()) ``` ```python # Client with full configuration client = bazooka.Client( auth=None, # requests auth object (HTTPBasicAuth, etc.) verify_ssl=True, # Enable/disable SSL verification allow_redirects=True, # Follow HTTP redirects correlation_id='my-correlation-id', # Correlation ID for request tracing correlation_id_header_name='correlationid', # Custom header name for correlation ID log_duration=True, # Enable request duration logging default_timeout=300 # Default timeout in seconds ) ``` -------------------------------- ### Full Request Parameters with ReliableSession Source: https://context7.com/infraguys/bazooka/llms.txt Demonstrates making a request with a comprehensive set of parameters, including method, URL, data, JSON payload, headers, cookies, files, authentication, timeout, redirects, proxies, SSL verification, and client certificates. ```python with ReliableSession() as session: response = session.request( method='POST', url='http://api.example.com/upload', data=None, json={'file_name': 'document.pdf'}, headers={'Content-Type': 'application/json'}, cookies={'session': 'abc123'}, files=None, auth=('user', 'pass'), timeout=60, allow_redirects=False, proxies={'http': 'http://proxy:8080'}, verify=True, cert='/path/to/cert.pem' ) ``` -------------------------------- ### Use ReliableSession as a Context Manager Source: https://context7.com/infraguys/bazooka/llms.txt Use `ReliableSession` as a context manager for automatic cleanup. This ensures that network operations are handled with automatic retries on network failures and 5XX errors. ```python with ReliableSession() as session: # Automatic retries on network failures and 5XX errors response = session.request( method='GET', url='http://api.example.com/data', params={'key': 'value'}, headers={'Accept': 'application/json'}, timeout=30, allow_redirects=True ) print(response.json()) ``` -------------------------------- ### Enable Request Duration Logging Source: https://context7.com/infraguys/bazooka/llms.txt Enable request duration logging by setting `session.log_duration = True`. This tracks the time taken for requests internally for logging purposes. ```python with ReliableSession() as session: session.log_duration = True response = session.request('POST', 'http://api.example.com/data', json={'key': 'value'}) # Duration is tracked internally for logging ``` -------------------------------- ### Bazooka Client with Correlation ID Source: https://github.com/infraguys/bazooka/blob/master/README.md Initialize the Bazooka client with a custom correlation ID. This ID can be used to match client requests with your business logic logs. ```python from bazooka import correlation client = bazooka.Client(correlation_id='my_correlation_id') print(client.get('http://example.com').json()) ``` -------------------------------- ### Trace Requests with Correlation IDs in Python Source: https://context7.com/infraguys/bazooka/llms.txt Include correlation IDs in request headers for tracing across services. A custom header name can be specified. Correlated logging is also supported. ```python import bazooka from bazooka.correlation import CorrelationLoggerAdapter import logging # Create client with correlation ID for distributed tracing client = bazooka.Client( correlation_id='order-12345-workflow', correlation_id_header_name='X-Correlation-ID' # Custom header name ) # All requests include the correlation header response = client.get('http://service-a.internal/validate') response = client.post('http://service-b.internal/process', json={'order_id': 12345}) response = client.put('http://service-c.internal/complete', json={'status': 'done'}) # Update correlation ID for a new workflow client.correlation_id = 'payment-67890-workflow' # Use CorrelationLoggerAdapter for correlated logging logger = logging.getLogger(__name__) correlated_logger = CorrelationLoggerAdapter(logger, 'order-12345-workflow') correlated_logger.info("Processing order") # Output: [correlation_id=order-12345-workflow] Processing order ``` -------------------------------- ### Handle HTTP Exceptions in Python Source: https://context7.com/infraguys/bazooka/llms.txt Catch specific Bazooka HTTP exceptions for granular error handling. All exceptions inherit from BaseHTTPException and provide access to the original cause and status code. ```python import bazooka from bazooka import exceptions client = bazooka.Client() try: response = client.get('http://api.example.com/resource', timeout=10) data = response.json() except exceptions.NotFoundError as e: # Handle 404 Not Found print(f"Resource not found: {e}") print(f"Status code: {e.code}") # 404 except exceptions.UnauthorizedError as e: # Handle 401 Unauthorized print(f"Authentication required: {e}") except exceptions.ForbiddenError as e: # Handle 403 Forbidden print(f"Access denied: {e}") except exceptions.BadRequestError as e: # Handle 400 Bad Request print(f"Invalid request: {e}") except exceptions.ConflictError as e: # Handle 409 Conflict print(f"Resource conflict: {e}") except exceptions.BaseHTTPException as e: # Handle any other HTTP error (4xx or 5xx) if e.code in range(400, 500): print(f"Client error {e.code}: {e}") else: print(f"Server error {e.code}: {e}") # Access the original requests.HTTPError original_error = e.cause ``` -------------------------------- ### Utility Function for Trailing Slashes Source: https://context7.com/infraguys/bazooka/llms.txt Demonstrates the usage of the `force_last_slash` utility function, which ensures that a given string path ends with a trailing slash. ```python print(force_last_slash('/api/users')) # /api/users/ print(force_last_slash('/api/users/')) # /api/users/ ``` -------------------------------- ### Propagate Request ID with Contextvars in Python Source: https://context7.com/infraguys/bazooka/llms.txt Use Python's contextvars for automatic request ID propagation. All requests within a context will include the X-Request-ID header. Explicitly set headers take priority. ```python from bazooka import request_id import bazooka # Generate and set a new request ID token = request_id.set_request_id() # Generates UUID automatically print(f"Current request ID: {request_id.get_request_id()}") # Or set a specific request ID token = request_id.set_request_id('custom-request-id-12345') # All requests within this context will include X-Request-ID header client = bazooka.Client() response = client.get('http://api.example.com/data') # Request automatically includes header: X-Request-ID: custom-request-id-12345 # Reset the context when done request_id.reset_request_id(token) # Explicit header takes priority over context response = client.get( 'http://api.example.com/data', headers={'X-Request-ID': 'explicit-id'} ) # Uses 'explicit-id' instead of context value ``` -------------------------------- ### Log Requests with Sensitive Data Masking in Python Source: https://context7.com/infraguys/bazooka/llms.txt Configure Bazooka client for curl-like request logging with automatic masking of sensitive headers. Optional body sanitization is available for PII or sensitive data. ```python from bazooka.client import Client, SensitiveMicroserviceSession # Standard client with curl logging (sensitive headers masked) # Headers like Authorization, Token, Cookie, X-API-Key are automatically masked client = Client( log_duration=True, correlation_id='api-call-001' ) # Logs: HTTP(s) request: curl -X 'GET' -H 'Authorization: ' http://api.example.com/data # Client with sensitive body logging (completely masks request body) # Use when request bodies contain PII or sensitive data sensitive_client = Client( session=SensitiveMicroserviceSession, log_duration=True, correlation_id='sensitive-api-call' ) response = sensitive_client.post( 'http://api.example.com/users', json={'ssn': '123-45-6789', 'credit_card': '4111111111111111'} ) # Logs: HTTP(s) request: curl -X 'POST' -H '...' -d '' http://api.example.com/users ``` -------------------------------- ### Module-Level HTTP Functions Source: https://context7.com/infraguys/bazooka/llms.txt Utilize module-level functions for making HTTP requests without explicit client instantiation. Each call creates a new `ReliableSession` with automatic retry logic. ```python import bazooka # Simple GET request response = bazooka.get('http://api.example.com/status') print(response.status_code) print(response.json()) ``` ```python # GET with query parameters response = bazooka.get('http://api.example.com/search', params={'q': 'python'}) ``` ```python # POST with JSON payload response = bazooka.post( 'http://api.example.com/items', json={'name': 'New Item', 'price': 29.99} ) ``` ```python # PUT request response = bazooka.put('http://api.example.com/items/1', data={'price': 39.99}) ``` ```python # PATCH request response = bazooka.patch('http://api.example.com/items/1', json={'status': 'sold'}) ``` ```python # DELETE request response = bazooka.delete('http://api.example.com/items/1') ``` ```python # Generic request method response = bazooka.request('GET', 'http://api.example.com/data', timeout=30) ``` -------------------------------- ### Use ReliableSession for Retries in Python Source: https://context7.com/infraguys/bazooka/llms.txt The ReliableSession class provides automatic retries for network failures and 5XX server errors. It can be used directly for more control over the session lifecycle. ```python from bazooka.sessions import ReliableSession ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.