Skip to contentSkip to navigationSkip to topbar
On this page

Creating Tasks and Accepting Reservations: Create a Task using the REST API


Recall the TaskRouter Task lifecycle:

Task Created → eligible Worker becomes available → Worker reserved → Reservation accepted → Task assigned to Worker.

(information)

Info

If you'd like to view the events happening in your Workspace at an Event Callback URL, please obtain a free endpoint URL(link takes you to an external page) then set the Event Callback URL in your Workspace to point there.

Setting Event Callback URL.

Before we create our first Task, make sure that our Worker Alice is in a non-available Activity state. Bob's Activity state won't matter right now, as we will create a Spanish language Task that he is not eligible to handle.

With your Workspace open in the TaskRouter web portal(link takes you to an external page), click 'Workers' then click to edit Alice and set her Activity to 'Offline'. Your Workers should look like this:

Ensure Alice is Offline.

To simulate reality, we'll create a Task using the REST API rather than the web portal. We'll add on to our run.py to create a task with our web server. Replace the {} with your Twilio AccountSid, Twilio AuthToken, WorkspaceSid, and WorkflowSid.

Download and extract Twilio's Python helper library(link takes you to an external page) into your working directory. This is required as we're utilizing the helper library to create a Task and will continue to use the library in subsequent steps. See the twilio-python documentation(link takes you to an external page).


run.py

runpy page anchor
1
from flask import Flask, request, Response
2
from twilio.rest import Client
3
4
app = Flask(__name__)
5
6
# Your Account Sid and Auth Token from twilio.com/user/account
7
account_sid = "{{ account_sid }}"
8
auth_token = "{{ auth_token }}"
9
workspace_sid = "{{ workspace_sid }}"
10
workflow_sid = "{{ workflow_sid }}"
11
12
client = Client(username=account_sid, password=auth_token)
13
14
@app.route("/assignment_callback", methods=['GET', 'POST'])
15
def assignment_callback():
16
"""Respond to assignment callbacks with empty 200 response"""
17
18
resp = Response({}, status=200, mimetype='application/json')
19
return resp
20
21
@app.route("/create_task", methods=['GET', 'POST'])
22
def create_task():
23
"""Creating a Task"""
24
task = client.taskrouter.workspaces(sid=workspace_sid).tasks.create(
25
workflow_sid=workflow_sid,
26
attributes='{"selected_language":"es"}'
27
)
28
print(task.attributes)
29
resp = Response({}, status=200, mimetype='application/json')
30
return resp
31
32
if __name__ == "__main__":
33
app.run(debug=True)

Next, reset your Workflow's Assignment Callback URL as shown below to point to your new, running Flask server's path.

Update assignment callback URL.

To generate a Task, visit the /create_task route we have just defined.

Alternatively, we can also create a Task using the command line utility curl, which should exist on any Mac or Linux workstation. Execute the following command at your terminal, making sure to replace the {} with your ngrok forwarding URL:

1
curl -X POST https://taskrouter.twilio.com/v1/Workspaces/{WorkspaceSid}/Tasks
2
--data-urlencode Attributes='{"selected_language": "es"}'
3
-d WorkflowSid={WorkflowSid}
4
-u {AccountSid}:{AuthToken}

If you don't have curl, you can run this request using an HTTP test tool or using the Task creation dialog in the TaskRouter web portal: with your Workspace open, click 'Tasks' then 'Create Task'.

To see our newly created Task in the TaskRouter web portal, with your Workspace open, click 'Tasks' in the main navigation. Notice that the Task has been added to the "Customer Care Requests - Spanish" Task Queue based on the Attributes we provided in the curl request. The Assignment Status is 'pending' because there is no available Worker that matches the Task Queue:

Newly created task assignment status is pending.

Make an Eligible Worker Available

make-an-eligible-worker-available page anchor

Look again at the TaskRouter Task lifecycle:

Task Created → eligible Worker becomes available → Worker reserved → Reservation accepted → Task assigned to Worker.

The first stage - 'Task Created' - is complete. To trigger an automatic Task Reservation, the next step is to bring an eligible Worker online.

Therefore, with your Workspace open in the TaskRouter web portal, click 'Workers', then click to edit Alice and set her Activity to 'Idle':

Set Alice to Idle.

When you hit save, Twilio will create a Reservation between Alice and our Task and you will receive a Webhook request at the Assignment Callback URL that we set up in the previous step. If you're using ngrok, open http://localhost:4040 in your web browser to see a detailed log of the request that Twilio made to your server, including all the parameters that your server might use to determine whether to accept a Reservation:

ngrok Request Log.

We're now one step further along the Task Reservation lifecycle:

Task Created → eligible Worker becomes available → Worker reserved → Reservation accepted → Task assigned to Worker.

Time to accept the Reservation.

Next: Accept a Reservation with the REST API »

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.