Best Practices
Tips for getting the most out of the Travelmode API.
Authentication
Secure Key Storage
Do:
import os
API_KEY = os.environ.get('TRAVELMODE_API_KEY')
Don't:
API_KEY = 'tm_abc123...' # Never hardcode keys!
Use Minimum Scopes
Only request the scopes you need:
read- For read-only applicationsread, write- For apps that create/update dataread, write, delete- Only when deletion is required
Rate Limiting
Implement Exponential Backoff
import time
def make_request(url, headers, max_retries=3):
for attempt in range(max_retries):
response = requests.get(url, headers=headers)
if response.status_code == 429:
wait_time = 2 ** attempt # 1, 2, 4 seconds
time.sleep(wait_time)
continue
return response
raise Exception("Max retries exceeded")
Cache Responses
Reduce API calls by caching data that doesn't change frequently:
from functools import lru_cache
@lru_cache(maxsize=100, ttl=300) # 5 minute cache
def get_trip(trip_id):
return requests.get(f"/api/trips/{trip_id}", headers=headers)
Revision Control
Always Include Expected Revision
For v1 API operations, include the expected revision to prevent conflicts:
{
"operation": "MOVE_EVENT",
"eventId": 5,
"newStartDateTime": "2024-06-16T14:00:00Z",
"expectedRevision": 42
}
Handle Revision Conflicts Gracefully
def update_with_retry(trip_id, operation):
for _ in range(3):
itinerary = get_itinerary(trip_id)
operation['expectedRevision'] = itinerary['revision']
response = apply_operation(trip_id, operation)
if response.status_code != 409:
return response
raise Exception("Could not resolve revision conflict")
Error Handling
Always Check Response Status
response = requests.post(url, json=data, headers=headers)
if not response.ok:
error = response.json().get('error', 'Unknown error')
logging.error(f"API error: {error}")
raise APIError(error)
Log API Errors
Maintain logs for debugging:
import logging
logging.basicConfig(level=logging.INFO)
response = requests.get(url, headers=headers)
logging.info(f"GET {url} - {response.status_code}")
if not response.ok:
logging.error(f"Error: {response.text}")
Performance
Batch Operations When Possible
Instead of multiple single requests:
# Slow - multiple requests
for event in events:
create_event(event)
# Better - if batch endpoint available
create_events_batch(events)
Use Pagination Efficiently
def get_all_trips():
trips = []
page = 1
while True:
response = get_trips(page=page, limit=50)
trips.extend(response['data'])
if page >= response['pagination']['totalPages']:
break
page += 1
return trips
Security
Rotate Keys Periodically
Create new keys and revoke old ones regularly.
Monitor API Usage
Track your API usage through rate limit headers:
remaining = response.headers.get('X-RateLimit-Remaining')
if int(remaining) < 100:
logging.warning(f"Low rate limit remaining: {remaining}")