# Python TomTicket Python TomTicket is a Python binding library for the TomTicket API, providing a clean and intuitive interface to interact with the TomTicket CRM platform. The library enables developers to integrate customer relationship management functionality directly into their Python applications through a simple, object-oriented API wrapper. The library follows a resource-based architecture where entities like clients and tickets are represented as Python classes with built-in CRUD operations. It handles authentication, request formatting, error handling, and response parsing automatically, allowing developers to focus on business logic rather than HTTP communication details. The library supports rate limiting awareness and provides comprehensive error types for different failure scenarios. ## Configuration Configure the TomTicket API client with your API key to authenticate all subsequent requests. ```python from tomticket import Tomticket # Set your API key for authentication Tomticket.api_key = "my-super-crazy-api-key" # Optional: Configure custom endpoint settings Tomticket.hostname = "custom-api.tomticket.com" # Custom hostname Tomticket.protocol = "https" # Protocol (default: https) # Configure multiple endpoints for load balancing Tomticket.endpoints = [ "https://api1.tomticket.com", "https://api2.tomticket.com" ] # Set custom request timeout (default: 10 seconds) from tomticket.request import Request Request.timeout = 30 ``` ## Creating a Client (Criar_Cliente) Create new customer records in the TomTicket CRM system using the Criar_Cliente resource class. ```python from tomticket import Tomticket, Criar_Cliente # Configure API credentials Tomticket.api_key = "your-api-key" # Create a new client instance with customer data new_client = Criar_Cliente( nome="John Doe", email="john.doe@example.com", telefone="555-1234", empresa="Acme Corp" ) # Save the client to TomTicket API # POST request to /criar_cliente/{token} try: result = new_client.save() print(f"Client created successfully: {result.to_dict}") except Exception as e: print(f"Failed to create client: {e}") ``` ## Creating a Ticket (Criar_Chamado) Create support tickets associated with existing customers using the Criar_Chamado resource class. ```python from tomticket import Tomticket, Criar_Chamado # Configure API credentials Tomticket.api_key = "your-api-key" # Create a new ticket instance new_ticket = Criar_Chamado( identificador_cliente="client-123", assunto="Technical Support Request", descricao="Unable to access dashboard after password reset", prioridade="alta", departamento="support" ) # Save the ticket to TomTicket API # POST request to /cria_chamado/{token}/{identificador_cliente} try: result = new_ticket.save() print(f"Ticket created: {result.to_dict}") except Exception as e: print(f"Failed to create ticket: {e}") ``` ## Direct HTTP Methods The Tomticket base class provides low-level HTTP methods for direct API access when working with custom endpoints. ```python from tomticket import Tomticket Tomticket.api_key = "your-api-key" # GET request - retrieve resources response = Tomticket.get("/clientes/%(token)s", page=1, limit=50) # POST request - create resources response = Tomticket.post("/criar_cliente/%(token)s", nome="Jane Smith", email="jane@example.com" ) # PUT request - update resources response = Tomticket.put("/cliente/%(token)s/123", nome="Jane Smith-Johnson" ) # DELETE request - remove resources response = Tomticket.delete("/cliente/%(token)s/123") # Note: %(token)s is automatically replaced with the api_key ``` ## Error Handling The library provides comprehensive error classes for handling various API failure scenarios. ```python from tomticket import Tomticket, Criar_Cliente from tomticket.errors import ( AuthenticationError, ResourceNotFound, BadRequestError, RateLimitExceeded, ServerError, ServiceUnavailableError, IntercomError ) Tomticket.api_key = "your-api-key" try: client = Criar_Cliente(nome="Test User", email="test@example.com") result = client.save() except AuthenticationError as e: # 401 Unauthorized or 403 Forbidden print(f"Authentication failed: {e.message}") except ResourceNotFound as e: # 404 Not Found print(f"Resource not found: {e.message}") except BadRequestError as e: # 400 Bad Request - missing/invalid parameters print(f"Invalid request: {e.message}") print(f"Error context: {e.context}") except RateLimitExceeded as e: # Rate limit exceeded print(f"Rate limit hit: {e.message}") # Check rate limit details print(f"Limit details: {Tomticket.rate_limit_details}") except ServerError as e: # 500 Internal Server Error print(f"Server error: {e.message}") except ServiceUnavailableError as e: # 503 Service Unavailable print(f"Service unavailable: {e.message}") except IntercomError as e: # Base exception for all TomTicket errors print(f"General error: {e.message}") ``` ## Rate Limiting Monitor and handle API rate limits using the built-in rate limit tracking functionality. ```python from tomticket import Tomticket, Criar_Cliente from tomticket.errors import RateLimitExceeded import time Tomticket.api_key = "your-api-key" def create_client_with_retry(client_data, max_retries=3): for attempt in range(max_retries): try: client = Criar_Cliente(**client_data) return client.save() except RateLimitExceeded: # Check rate limit details from response headers rate_info = Tomticket.rate_limit_details print(f"Rate limit: {rate_info.get('remaining')}/{rate_info.get('limit')}") if 'reset_at' in rate_info: wait_time = (rate_info['reset_at'] - time.time()) + 1 print(f"Waiting {wait_time} seconds until reset...") time.sleep(max(wait_time, 1)) else: time.sleep(60) # Default wait raise Exception("Max retries exceeded") # Usage result = create_client_with_retry({ "nome": "Rate Limited User", "email": "ratelimit@example.com" }) ``` ## Resource Attributes and Serialization Work with resource attributes using the built-in serialization and deserialization capabilities. ```python from tomticket import Criar_Cliente, Criar_Chamado # Create resource with attributes client = Criar_Cliente( nome="Alice Johnson", email="alice@example.com", telefone="555-9876", custom_field="custom_value" ) # Access attributes dictionary (only changed attributes are included) print(f"Changed attributes: {client.attributes}") # Convert to full dictionary representation print(f"Full data: {client.to_dict}") # Populate from dictionary data = { "nome": "Bob Williams", "email": "bob@example.com", "empresa": "Tech Corp" } another_client = Criar_Cliente() another_client.from_dict(data) # Create from API response api_response = {"id": "123", "nome": "Charlie", "email": "charlie@example.com"} loaded_client = Criar_Cliente.from_api(api_response) ``` ## Logging and Debugging Enable debug logging to troubleshoot API requests and responses. ```python import logging from tomticket import Tomticket, Criar_Cliente # Configure logging for debugging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('tomticket.request') logger.setLevel(logging.DEBUG) Tomticket.api_key = "your-api-key" # All requests will now log detailed information: # - Request method and URL # - Request headers # - Request parameters # - Response encoding and status code # - Response content client = Criar_Cliente(nome="Debug Test", email="debug@example.com") result = client.save() # Example log output: # DEBUG:tomticket.request:Sending POST request to: https://api.tomticket.com/criar_cliente/your-api-key # DEBUG:tomticket.request: headers: {'User-Agent': 'python-tomticket/1.0', 'Accept': 'application/json'} # DEBUG:tomticket.request: params: {'nome': 'Debug Test', 'email': 'debug@example.com'} # DEBUG:tomticket.request:Response received from https://api.tomticket.com/criar_cliente/your-api-key # DEBUG:tomticket.request: encoding=utf-8 status:200 ``` ## Summary Python TomTicket provides a straightforward way to integrate with the TomTicket CRM API for customer and ticket management. The primary use cases include creating customer records through the Criar_Cliente class, generating support tickets via Criar_Chamado, and performing custom API operations using direct HTTP methods. The library handles authentication transparently by injecting the API key into request URLs and manages response parsing with automatic JSON deserialization. Integration patterns typically involve configuring the global Tomticket.api_key at application startup, then instantiating resource objects with attribute data and calling save() to persist them to the API. For robust applications, implementing error handling with the provided exception hierarchy ensures graceful degradation when API issues occur. The rate limit tracking feature enables building resilient applications that respect API quotas, while the logging capabilities facilitate debugging during development and troubleshooting in production environments.