Create Ticket Flow¶
This example demonstrates a complete workflow for creating a ticket with comments and attachments.
Overview¶
We'll walk through:
- Creating a new ticket
- Adding a comment
- Uploading an attachment
- Updating the ticket status
Prerequisites¶
import requests
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.toptickets.app/v1"
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
Step 1: Create a Ticket¶
Create a new support ticket for a customer issue:
# Create ticket
ticket_data = {
"customer_name": "Jane Smith",
"customer_email": "jane.smith@example.com",
"subject": "Unable to export data from dashboard",
"description": """
I'm trying to export my monthly reports from the dashboard, but when I click
the Export button, nothing happens. I've tried Chrome and Firefox.
Steps to reproduce:
1. Go to Dashboard > Reports
2. Select date range
3. Click "Export to CSV"
4. Nothing downloads
This is blocking my month-end reporting.
""".strip(),
"priority": "high",
"category": "Technical"
}
response = requests.post(
f"{BASE_URL}/tickets",
headers=HEADERS,
json=ticket_data
)
ticket = response.json()
ticket_id = ticket["id"]
print(f"Created ticket: {ticket['ticket_display_id']}")
print(f"Ticket ID: {ticket_id}")
curl -X POST "https://api.toptickets.app/v1/tickets" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"customer_name": "Jane Smith",
"customer_email": "jane.smith@example.com",
"subject": "Unable to export data from dashboard",
"description": "I am trying to export my monthly reports from the dashboard, but when I click the Export button, nothing happens. I have tried Chrome and Firefox.\n\nSteps to reproduce:\n1. Go to Dashboard > Reports\n2. Select date range\n3. Click Export to CSV\n4. Nothing downloads\n\nThis is blocking my month-end reporting.",
"priority": "high",
"category": "Technical"
}'
Response:
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"ticket_number": 1050,
"ticket_display_id": "TKT-1050",
"customer_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"subject": "Unable to export data from dashboard",
"status": "new",
"priority": "high",
"category": "Technical",
"created_at": "2025-01-15T10:30:00Z"
}
Step 2: Add an Initial Response¶
Add a comment acknowledging the issue:
comment_data = {
"content": """
Hi Jane,
Thank you for reporting this issue. I understand the export feature isn't working
and this is blocking your month-end reporting.
I've escalated this to our engineering team as a priority issue. While we
investigate, could you try the following workaround:
1. Go to Dashboard > Reports
2. Use the "Print" option (Ctrl+P)
3. Select "Save as PDF" in the print dialog
This should give you a PDF version of your report. I'll update you as soon as
we have a fix for the CSV export.
Best regards,
Support Team
""".strip(),
"is_internal": False
}
response = requests.post(
f"{BASE_URL}/tickets/{ticket_id}/comments",
headers=HEADERS,
json=comment_data
)
comment = response.json()
print(f"Added comment: {comment['id']}")
curl -X POST "https://api.toptickets.app/v1/tickets/123e4567-e89b-12d3-a456-426614174000/comments" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "Hi Jane,\n\nThank you for reporting this issue. I understand the export feature is not working and this is blocking your month-end reporting.\n\nI have escalated this to our engineering team as a priority issue.\n\nBest regards,\nSupport Team",
"is_internal": false
}'
Step 3: Add an Internal Note¶
Add a private note for other agents:
internal_note = {
"content": """
Engineering ticket created: ENG-4521
Root cause identified: The export endpoint is timing out for large datasets.
Fix ETA: 2 days
Workaround confirmed working for this customer.
""".strip(),
"is_internal": True # Only visible to agents
}
response = requests.post(
f"{BASE_URL}/tickets/{ticket_id}/comments",
headers=HEADERS,
json=internal_note
)
print("Added internal note")
curl -X POST "https://api.toptickets.app/v1/tickets/123e4567-e89b-12d3-a456-426614174000/comments" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"content": "Engineering ticket created: ENG-4521\n\nRoot cause identified: The export endpoint is timing out for large datasets.\nFix ETA: 2 days",
"is_internal": true
}'
Step 4: Upload an Attachment¶
Attach a screenshot or log file:
# Upload a screenshot
with open("export_error_screenshot.png", "rb") as file:
response = requests.post(
f"{BASE_URL}/tickets/{ticket_id}/attachments",
headers={"Authorization": f"Bearer {API_KEY}"}, # No Content-Type for multipart
files={"file": ("screenshot.png", file, "image/png")}
)
attachment = response.json()
print(f"Uploaded attachment: {attachment['filename']}")
print(f"Size: {attachment['size_bytes']} bytes")
Response:
{
"id": "789f0123-g45h-67i8-j901-234567890abc",
"ticket_id": "123e4567-e89b-12d3-a456-426614174000",
"filename": "screenshot.png",
"content_type": "image/png",
"size_bytes": 145230,
"created_at": "2025-01-15T10:35:00Z"
}
Step 5: Update Ticket Status¶
Change the status to indicate we're working on it:
update_data = {
"status": "open",
"assigned_team_id": "550e8400-e29b-41d4-a716-446655440000" # Technical Support team
}
response = requests.patch(
f"{BASE_URL}/tickets/{ticket_id}",
headers=HEADERS,
json=update_data
)
updated_ticket = response.json()
print(f"Ticket status: {updated_ticket['status']}")
Complete Python Script¶
Here's the full script combining all steps:
import requests
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.toptickets.app/v1"
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
def create_ticket_with_response():
"""Create a complete ticket workflow."""
# 1. Create ticket
ticket_response = requests.post(
f"{BASE_URL}/tickets",
headers=HEADERS,
json={
"customer_name": "Jane Smith",
"customer_email": "jane.smith@example.com",
"subject": "Unable to export data from dashboard",
"description": "Export feature not working. Blocking month-end reporting.",
"priority": "high",
"category": "Technical"
}
)
ticket_response.raise_for_status()
ticket = ticket_response.json()
ticket_id = ticket["id"]
print(f"Created: {ticket['ticket_display_id']}")
# 2. Add public response
requests.post(
f"{BASE_URL}/tickets/{ticket_id}/comments",
headers=HEADERS,
json={
"content": "Thank you for reporting this. We're investigating.",
"is_internal": False
}
).raise_for_status()
print("Added public comment")
# 3. Add internal note
requests.post(
f"{BASE_URL}/tickets/{ticket_id}/comments",
headers=HEADERS,
json={
"content": "Engineering notified. ENG-4521 created.",
"is_internal": True
}
).raise_for_status()
print("Added internal note")
# 4. Update status
requests.patch(
f"{BASE_URL}/tickets/{ticket_id}",
headers=HEADERS,
json={"status": "open"}
).raise_for_status()
print("Updated status to 'open'")
return ticket
if __name__ == "__main__":
ticket = create_ticket_with_response()
print(f"\nTicket {ticket['ticket_display_id']} created successfully!")
Error Handling¶
Add proper error handling for production use:
def create_ticket_safely(ticket_data):
"""Create ticket with error handling."""
try:
response = requests.post(
f"{BASE_URL}/tickets",
headers=HEADERS,
json=ticket_data,
timeout=30
)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
raise Exception("Invalid API key")
elif e.response.status_code == 403:
raise Exception("Missing tickets:write scope")
elif e.response.status_code == 422:
errors = e.response.json().get("detail", [])
raise Exception(f"Validation error: {errors}")
else:
raise
except requests.exceptions.Timeout:
raise Exception("Request timed out")
except requests.exceptions.ConnectionError:
raise Exception("Could not connect to API")
Next Steps¶
- Ticket Management - Learn to list, filter, and bulk update tickets
- API Reference: Tickets - Full endpoint documentation
- Error Handling - Comprehensive error handling guide