1WWW::Twilio::API(3)   User Contributed Perl Documentation  WWW::Twilio::API(3)
2
3
4

NAME

6       WWW::Twilio::API - Accessing Twilio's REST API with Perl
7

SYNOPSIS

9         use WWW::Twilio::API;
10
11         my $twilio = WWW::Twilio::API->new(AccountSid => 'AC12345...',
12                                            AuthToken  => '1234567...');
13
14         ## make a phone call
15         $response = $twilio->POST( 'Calls',
16                                    From => '1234567890',
17                                    To   => '8905671234',
18                                    Url  => 'http://domain.tld/send_twiml' );
19
20         print $response->{content};
21

COMPATIBILITY NOTICE

23       This section is for existing WWW::Twilio::API users considering an
24       upgrade from WWW::Twilio::API versions prior to 0.15. If you're new to
25       WWW::Twilio::API you may safely unconcern yourself with this section
26       and move on to "DESCRIPTION" below.
27
28       WWW::Twilio::API since version 0.15 defaults to Twilio's 2010-04-01
29       API. That is the only substantive change from version 0.14. If you are
30       one of those types of people who must have the latest version of
31       everything, you have two options:
32
33       ·   Before you upgrade to 0.15, change all of your new() method calls
34           to explicitly use API_VERSION as '2008-08-01', like this:
35
36             my $twilio = WWW::Twilio::API->new
37               ( AccountSid  => 'AC12345...',
38                 AuthToken   => '1234567...',
39                 API_VERSION => '2008-08-01' );  ## <-- add this line here
40
41           Now you may safely upgrade WWW::Twilio::API and stay current. You
42           can then update your individual Twilio API calls piecemeal at your
43           leisure.
44
45       ·   Go through all of your existing GET, PUT, POST, and DELETE calls
46           and make sure that they're up-to-date with Twilio's new
47           '2010-04-01' API (the new API is a little simpler in some ways than
48           the 2008 version) and set the API_VERSION to '2010-04-01'. Test
49           that your code all works with the new API.
50
51           Now you can safely upgrade WWW::Twilio::API.
52

DESCRIPTION

54       WWW::Twilio::API aims to make connecting to and making REST calls on
55       the Twilio API easy, reliable, and enjoyable.
56
57       You should have ready access to Twilio's API documentation in order to
58       use WWW::Twilio::API.
59
60       WWW::Twilio::API knows almost nothing about the Twilio API itself other
61       than the authentication and basic format of the REST URIs.
62
63       Users already familiar with the API may skip the following section
64       labeled "TWILIO API" and move to the "METHODS" section. Beginners
65       should definitely continue here.
66

TWILIO API

68       This section is meant to help you understand how to read the Twilio API
69       documentation and translate it into WWW::Twilio::API calls.
70
71       The Twilio API documentation is found here:
72
73         http://www.twilio.com/docs/api/rest/
74
75       The Twilio REST API consists of requests and responses. Requests
76       consist of Resources and Properties. Responses consist of HTTP status
77       codes and often content. What resources, properties, status codes and
78       content you should use is what the Twilio REST API documentation
79       covers.
80
81   Getting started
82       While what comes next is covered in the Twilio documentation, this may
83       help some people who want a quicker start. Head over to twilio.com and
84       signup for a free demo account. Once you've signed up, visit
85
86         https://www.twilio.com/user/account/
87
88       where you'll find your Account Sid and AuthToken. Your Account Sid and
89       AuthToken are essentially your username and password for the Twilio
90       API. Note that these are not the same credentials as your Twilio
91       account login username and password, which is an email address and a
92       password you've selected. You'll never use your email address and
93       password in the API--those are only for logging into your Twilio web
94       account at twilio.com.
95
96       Once you've signed up, be sure to add at least one phone number to your
97       account by clicking "Numbers" and then "Verify a number". Be sure
98       you're near the phone whose number you entered, as Twilio will make an
99       automated call to verify it. Once you've added a phone number, you can
100       start playing with Twilio's Calls API, which we'll be using in some of
101       our examples below.
102
103   Twilio requests
104       Twilio request resources look just like a URL you might enter into your
105       browser to visit a secure web page:
106
107         https://api.twilio.com/2010-04-01/Accounts/{YourAccountSid}/Calls
108
109       In addition to the URI above, if the request is a POST (as opposed to a
110       GET), you would also pass along certain key/value pairs that represent
111       the resources's properties.
112
113       So, to place a call using Twilio, your resource is:
114
115         https://api.twilio.com/2010-04-01/Accounts/{YourAccountSid}/Calls
116
117       and the set of properties for this resource might be:
118
119         To   = 5558675309
120         From = 4158675309
121         Url  = http://www.myapp.com/myhandler
122
123       You can see the list of properties for the Calls resource here:
124
125         http://www.twilio.com/docs/api/rest/making_calls
126
127       Further down in "METHODS" we'll cover how this works using
128       WWW::Twilio::API, but here's a teaser to help you see how easy your job
129       as a budding Twilio developer will be:
130
131         ## call Jenny
132         $twilio->POST('Calls',
133                       To => '5558675309',
134                       From => '4158675309',
135                       Url => 'http://www.myapp.com/myhandler');
136
137   Twilio responses
138       Once you have made a request to a Twilio resource, the Twilio API
139       server will send a response back to you. The response consists of an
140       HTTP status code (e.g., 200, 302, 404, 500) and some content (usually
141       an XML document).
142
143       For example, if we made the POST to the Calls resource above, and if
144       everything went well, we'd receive a status of 200 and an XML document
145       like this, telling us that everything went great:
146
147         <?xml version="1.0"?>
148         <TwilioResponse>
149           <Call>
150             <Sid>CAxxxxxxxxxx</Sid>
151             <DateCreated>Wed, 10 Aug 2011 04:38:16 +0000</DateCreated>
152             <DateUpdated>Wed, 10 Aug 2011 04:38:16 +0000</DateUpdated>
153             <ParentCallSid/>
154             <AccountSid>ACxxxxxxxx</AccountSid>
155             <To>+15558675309</To>
156             <ToFormatted>(555) 867-5309</ToFormatted>
157             <From>+14158675309</From>
158             <FromFormatted>(415) 867-5309</FromFormatted>
159             <PhoneNumberSid>PNxxxxxxxxxxx</PhoneNumberSid>
160             <Status>queued</Status>
161             <StartTime/>
162             <EndTime/>
163             <Duration/>
164             <Price/>
165             <Direction>outbound-api</Direction>
166             <AnsweredBy/>
167             <ApiVersion>2010-04-01</ApiVersion>
168             <Annotation/>
169             <ForwardedFrom/>
170             <GroupSid/>
171             <CallerName/>
172             <Uri>/2010-04-01/Accounts/ACxxxxxxxxx/Calls/CAxxxxxx</Uri>
173             <SubresourceUris>
174               <Notifications>/2010-04-01/Accounts/ACxxxxxxxxxxx/Calls/CAxxxxxxx/Notifications</Notifications>
175               <Recordings>/2010-04-01/Accounts/ACxxxxxxxxxx/Calls/CAxxxxxx/Recordings</Recordings>
176             </SubresourceUris>
177           </Call>
178         </TwilioResponse>
179
180       Don't let all this HTTP request/response (or XML) business worry you:
181       WWW::Twilio::API makes requests and handles responses for you, so you
182       don't have to get involved with all the details. Besides, you can also
183       opt to have Twilio send its responses to you in CSV, JSON, or HTML.
184
185   Using WWW::Twilio::API
186       Now that we have a basic understanding of how Twilio's REST API works,
187       we can translate the API into WWW::Twilio::API method calls. Doing this
188       is trivial:
189
190       1.  Find the API resource you want to do (e.g., make a call, check
191           accounts, verify a caller id, etc.) in the manual. Look at the Base
192           Resource URI, and take note of everything after
193           "/2010-04-01/Accounts/{YourAccountSid}/" (e.g., Calls).
194
195           Please see the exception for Accounts above in the section "API
196           resource name" under the GET method.
197
198           This is your API resource: "Calls"
199
200       2.  Determine which HTTP method you need to make to make the call. For
201           example, to view details about a call, you'll use the GET method
202           for the Calls resource. To make a new call, you'll use the POST
203           method for the Calls resource. Both use the same resource, but
204           different HTTP methods, depending on what you want to do.
205
206           This is your API method. "GET"
207
208       3.  Determine the resource properties you'll need to send. Most GET
209           methods don't require any parameters, but may require additional
210           information in the resource (e.g., to view details about all calls,
211           your resource will simply be "Calls", whereas to look at a
212           particular call, your resource will look like
213           "Calls/CA42ed11f93dc08b952027ffbc406d0868")
214
215           If you're using a POST method to make your call, consult the Twilio
216           documentation for making calls and you should see a table under
217           POST Parameters describing the required and optional parameters you
218           may send in your API call.
219
220           These are your resource parameters for the Calls API: From =
221           '1234567890', To = '5558675309', Url =
222           'http://perlcode.org/cgi-bin/twilio'.
223
224           Also, if you want your response in something other than XML, you
225           may add any of 'csv', 'json', or 'html' (any representation found
226           at http://www.twilio.com/docs/api/rest/tips) to the Twilio API
227           call:
228
229             ## return JSON in $response->{content}
230             $response = $twilio->POST('Calls.json',
231                                       To   => '5558675309',
232                                       From => '1234567890',
233                                       Url  => 'http://twimlets.com/callme');
234
235             ## CSV list of recordings
236             $response = $twilio->POST('Recordings.csv');
237
238           See "Alternative resource representations" below.
239
240       4.  Create a WWW::Twilio::API object and make the call using the API
241           method, API resource, and resource parameters. The pattern you'll
242           follow looks like this:
243
244             $response = $twilio_object->METHOD(Resource, %parameters);
245
246           For these examples, see the following pages in Twilio's API
247           documentation:
248
249             http://www.twilio.com/docs/api/rest/call
250             http://www.twilio.com/docs/api/rest/making_calls
251
252           Here are the examples:
253
254             ## create an object
255             my $twilio = new WWW::Twilio::API( AccountSid => '{your account sid}',
256                                                AuthToken  => '{your auth token}' );
257
258             ## view a list of calls we've made
259             $response = $twilio->GET('Calls.json');
260             print $response->{content};  ## this is a JSON document
261
262             ## view one particular call we've made
263             $response = $twilio->GET('Calls/CA42ed11f93dc08b952027ffbc406d0868.csv');
264             print $response->{content};  ## this is a CSV document
265
266             ## make a new call
267             $response = $twilio->POST('Calls',
268                                       From => '1234567890',
269                                       To   => '3126540987',
270                                       Url  => 'http://perlcode.org/cgi-bin/twilio');
271             print $response->{content};  ## this is an XML document
272
273       5.  Examine the response to make sure things went ok. If your response
274           code isn't 200 (or whatever the normal code for the resource and
275           method you're using is), something went wrong and you should check
276           for any error codes:
277
278             $response = $twilio->POST('Calls');  ## I forgot my parameters!
279
280             unless( $response->{code} == 200 ) {
281               die <<_UNTIMELY_;
282               Error: ($response->{code}): $response->{message}
283               $response->{content}
284             _UNTIMELY_
285             }
286
287           which would print:
288
289             (400): Bad Request
290             <?xml version="1.0"?>
291             <TwilioResponse>
292               <RestException>
293                 <Status>400</Status>
294                 <Message>No called number is specified</Message>
295                 <Code>21201</Code>
296                 <MoreInfo>http://www.twilio.com/docs/errors/21201</MoreInfo>
297               </RestException>
298             </TwilioResponse>
299
300           See how useful that is? Everything you need to know: "No called
301           number is specified" might jog your memory into realizing that you
302           didn't specify anything else either.
303
304           Once we've fixed everything up, we can try again:
305
306             ## call Jenny
307             $response = $twilio->POST('Calls',
308                                       To   => '5558675309',
309                                       From => '3126540987',
310                                       Url  => 'http://perlcode.org/cgi-bin/twilio');
311
312             print $response->{content};
313
314           which now prints:
315
316             <?xml version="1.0"?>
317             <TwilioResponse>
318               <Call>
319                 <Sid>CAxxxxxxxxxx</Sid>
320                 <DateCreated>Wed, 10 Aug 2011 04:38:16 +0000</DateCreated>
321                 <DateUpdated>Wed, 10 Aug 2011 04:38:16 +0000</DateUpdated>
322                 <ParentCallSid/>
323                 <AccountSid>ACxxxxxxxx</AccountSid>
324                 <To>+15558675309</To>
325                 <ToFormatted>(555) 867-5309</ToFormatted>
326                 <From>+13126540987</From>
327                 <FromFormatted>(312) 654-0987</FromFormatted>
328                 <PhoneNumberSid>PNxxxxxxxxxxx</PhoneNumberSid>
329                 <Status>queued</Status>
330                 <StartTime/>
331                 <EndTime/>
332                 <Duration/>
333                 <Price/>
334                 <Direction>outbound-api</Direction>
335                 <AnsweredBy/>
336                 <ApiVersion>2010-04-01</ApiVersion>
337                 <Annotation/>
338                 <ForwardedFrom/>
339                 <GroupSid/>
340                 <CallerName/>
341                 <Uri>/2010-04-01/Accounts/ACxxxxxxxxx/Calls/CAxxxxxx</Uri>
342                 <SubresourceUris>
343                   <Notifications>/2010-04-01/Accounts/ACxxxxxxxxxxx/Calls/CAxxxxxxx/Notifications</Notifications>
344                   <Recordings>/2010-04-01/Accounts/ACxxxxxxxxxx/Calls/CAxxxxxx/Recordings</Recordings>
345                 </SubresourceUris>
346               </Call>
347             </TwilioResponse>
348
349           Excellent! This pattern works for all API methods (see note on
350           "Accounts" in the "API resource name" section above under the GET
351           method).
352
353   What's Missing? TwiML
354       The missing magical piece is the TwiML, which is supplied by the Url
355       resource parameter you may have noticed above in the Calls resource
356       examples.
357
358       TwiML controls the flow of your call application, including responding
359       to key presses, playing audio files, or "reading" text-to-speech
360       phrases to the person on the other end of the line.
361
362       To continue the Calls example, you will need to give the Calls resource
363       a URL that returns TwiML (see http://www.twilio.com/docs/api/twiml/).
364       This is not hard, but it does require you to have a web server
365       somewhere on the Internet that can reply to GET or POST requests.
366
367       Twilio provides a set of canned TwiML applications for you to use for
368       free on their server, or you may download them and modify them as you
369       wish. Twilio's "Twimlets" may be found here:
370
371         http://labs.twilio.com/twimlets/
372
373       A TwiML document looks like this:
374
375         <?xml version="1.0" encoding="UTF-8" ?>
376         <Response>
377           <Say>Hello World</Say>
378           <Play>http://api.twilio.com/Cowbell.mp3</Play>
379         </Response>
380
381       When the Twilio API's Calls resource is invoked with a URL that returns
382       an XML document like the above, Twilio's servers will first "read" the
383       phrase "Hello World" to the caller using a text-to-speech synthesizer.
384       It will then download Cowbell.mp3 and play it to the caller.
385
386       Note that the URL you supply may be a static file, or it may be a
387       script or other handler that can receive a GET or POST from Twilio's
388       API server.
389
390       If you don't have your own web server, one location you might consider
391       temporarily is one used in Twilio's own examples, which simply creates
392       a TwiML document based on whatever arguments you send it:
393
394         http://twimlets.com/message?Message=$MSG
395
396       where $MSG is a URI encoded string of what you want Twilio to say when
397       the person who is called picks up the phone.
398
399       For example, you could say:
400
401         http://twimlets.com/message?Message=Nice+to+meet+you
402
403       and when you did this:
404
405         $twilio->POST('Calls',
406                       From => '1112223333',
407                       To   => '1231231234',
408                       Url  => 'http://twimlets.com/message?Message=Nice+to+meet+you');
409
410       Twilio's API would call '123-123-1234' and when someone answers, they
411       will hear "Nice to meet you" in a somewhat computerized voice.
412
413       Go ahead and follow the twimlets.com link above and view the source in
414       your browser window. It's just a plain XML document.
415
416       See http://www.twilio.com/docs/api_reference/TwiML/ for full TwiML
417       documentation.
418

METHODS

420       This section describes all the available methods in detail.
421
422   new
423       Creates a new Twilio object.
424
425       Available parameters:
426
427       AccountSid
428           Your account sid (begins with 'AC')
429
430       AuthToken
431           Your account auth token.
432
433       API_VERSION
434           Defaults to '2010-04-01'. You won't need to set this unless: a)
435           Twilio updates their API, and b) you want to take advantage of it
436           or c) you've coded against an older API version and need to set
437           this for backward compatibility.
438
439           NOTE: WWW::Twilio::API prior to version 0.15 defaulted to
440           '2008-08-01'; if you're upgrading WWW::Twilio::API, see
441           "COMPATIBILITY" section at the top of this documentation.
442
443       LWP_Callback
444           No default. This is a code reference you may pass in. The code
445           reference will receive the internal LWP::UserAgent object
446           immediately after it is created so you can set up proxies,
447           timeouts, etc.
448
449       utf8
450           If set to a true value, will use URI::Escape's "uri_escape_utf8"
451           instead of "uri_escape".
452
453       Example:
454
455         my $twilio = new WWW::Twilio::API
456           ( AccountSid => 'AC...',
457             AuthToken  => '...',
458             API_VERSION => '2008-08-01',
459             LWP_Callback => sub { shift->timeout(30) } );
460
461   General API calls
462       All API calls are of the form:
463
464         $twilio_object->METHOD('Resource', %parameters)
465
466       where METHOD is one of GET, POST, PUT, or DELETE, and 'Resource' is the
467       resource URI after removing the leading
468       "/2010-04-01/Accounts/{YourAccountSid}/".
469
470       Note that you do not need to URI encode the parameters;
471       WWW::Twilio::API handles that for you (this just means that you don't
472       have to do anything special with the parameters you give the
473       WWW::Twilio::API object).
474
475         Note: There is one exception to URI encoding: when you are passing a
476         I<Url> parameter (e.g., to the I<Calls> resource), and that URL
477         contains a B<GET> query string, that query string needs to be URI
478         encoded. See the F<examples.pl> file with this distribution for an
479         example of that.
480
481       Each of GET, POST, PUT, and DELETE returns a hashref with the call
482       results, the most important of which is the content element. This is
483       the untouched, raw response of the Twilio API server, suitable for you
484       to do whatever you want with it. For example, you might want to hand it
485       off to an XML parser:
486
487         $resp = $twilio->GET('Calls');
488
489         use XML::LibXML;
490         my $parser = new XML::LibXML;
491         my $doc = $parser->parse_string($resp->{content});
492         ... do some processing on $doc now ...
493
494       What you do with the results is up to you.
495
496       Here are the (current) elements in the response:
497
498       content
499           Contains the response content (in XML, CSV, JSON, or HTML if
500           specified).
501
502       code
503           Contains the HTTP status code. You should check this after each
504           call to make sure it's what you'd expect (according to the API).
505           Most successful responses will be '200', but some are '204' or
506           others.
507
508       message
509           A brief HTTP status message, corresponding to the status code. For
510           200 codes, the message will be "OK". For "400" codes, the message
511           will be "Bad Request" and so forth.
512
513           For the curious, a complete list of HTTP status codes, messages and
514           explanations may be found here:
515
516             http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
517
518       Example:
519
520         $response = $twilio->GET('Calls/CA42ed11f93dc08b952027ffbc406d0868');
521
522       $response is a hashref that looks like this:
523
524         {
525           content => '<an xml string>',
526           code    => '200',
527           message => 'OK',
528         }
529
530   Alternative resource representations
531       By default, results come back in XML and are stored in the response's
532       content element. You may wish to have results returned in comma-
533       separated value format. To do this, simply append '.csv' to the end of
534       your API resource:
535
536         $resp = $twilio->GET('Calls.csv');
537
538       The same thing works for JSON and HTML: simply append '.json' or
539       '.html' respectively to the end of your API resource. See
540       http://www.twilio.com/docs/api/rest/tips for other possible
541       representations.
542
543   GET
544       Sends a GET request to the Twilio REST API.
545
546       Available parameters:
547
548       API resource name
549           The first argument to GET should always be the API resource name
550           you want to invoke. Examples include Accounts, Calls, Recordings
551           and so on. It may be a multi-level resource name, such as
552           Recordings/{RecordingSid}/Transcriptions. It may also have a
553           particular instance you want to see, such as
554           Calls/CA42ed11f93dc08b952027ffbc406d0868.
555
556           The one exception is the Accounts resource. For the Accounts
557           resource, you may specify 'Accounts', an empty string, or nothing
558           (for GET requests only), since there is nothing after the common
559           URI base ("/2010-04-01/Accounts/{YourAccountSid}"). Using Accounts
560           is recommended for orthogonality with other resources, and to be
561           clear, especially when you're using a POST method.
562
563           You may wish to append '.csv', '.json' or '.html' to the API
564           resource to receive results in CSV (comma-separated values), JSON,
565           or HTML formats, instead of the default XML. See "Alternative
566           resource representations" above.
567
568       API resource parameters
569           Each API resource takes zero or more key-value pairs as parameters.
570           See the POST method below for examples.
571
572       None of the following examples use resource parameters; see the POST
573       section for examples illustrating the use of resource parameters.
574
575       GET examples:
576
577         ## get a list of all calls
578         $response = $twilio->GET('Calls');
579
580         ## get a single call instance in CSV format
581         $response = $twilio->GET('Calls/CA42ed11f93dc08b952027ffbc406d0868.csv');
582
583         ## get a recording list in XML
584         $response = $twilio->GET('Recordings');
585
586         ## get a recording list in HTML
587         $response = $twilio->GET('Recordings.html');
588
589   POST
590       Sends a POST request to the Twilio REST API.
591
592       Available parameters:
593
594       Same as GET.
595
596       The following examples illustrate the use of an API resource with
597       resource parameters. Be sure to check Twilio's API for correct
598       arguments for the current Twilio API version.
599
600         ## validate a CallerId: 'OutgoingCallerIds' is the API resource and
601         ## everything else are resource parameters
602         $response = $twilio->POST('OutgoingCallerIds',
603                                   FriendlyName => "Some Caller Id",
604                                   PhoneNumber  => '1234567890');
605
606         ## make a phone call (note: this is for Twilio's 2008-08-01 API)
607         $response = $twilio->POST('Calls',
608                                   Caller => '1231231234',
609                                   Called => '9081231234',
610                                   Url    => 'http://some.where/handler');
611
612         ## send an SMS message
613         $response = $twilio->POST('SMS/Messages',
614                                   From => '1231231234',
615                                   To   => '9081231234',
616                                   Body => "Hey, let's have lunch" );
617
618   PUT
619       Sends a PUT request to the Twilio REST API.
620
621       Available parameters:
622
623       Same as GET.
624
625   DELETE
626       Sends a DELETE request to the Twilio REST API.
627
628       Available parameters:
629
630       Same as GET.
631
632       Example:
633
634         $response = $twilio->DELETE('Recordings/RE41331862605f3d662488fdafda2e175f');
635

API CHANGES

637       Versions of WWW::Twilio::API prior to 0.15 defaulted to 2008-08-01. API
638       calls since WWW::Twilio::API version 0.15 and later are against
639       Twilio's 2010-04-01 API. If you need to call against a different API,
640       you may pass it into the constructor:
641
642         $t = WWW::Twilio::API->new( AccountSid  => '...',
643                                     AuthToken   => '...',
644                                     API_VERSION => 'YYYY-MM-DD' );
645
646       where 'YYYY-MM-DD' is the new (or old) API version.
647

EXAMPLES

649       There are plenty of examples strewn in the documentation above. If you
650       need more, see the examples.pl file with this distribution; also please
651       see Twilio's own REST API documentation and TwiML documentation.
652

SEE ALSO

654       LWP(1), <http://www.twilio.com/>
655

AUTHOR

657       Scott Wiersdorf, <scott@perlcode.org>
658
660       Copyright (C) 2009–2012 by Scott Wiersdorf
661
662       This library is free software; you can redistribute it and/or modify it
663       under the same terms as Perl itself, either Perl version 5.8.1 or, at
664       your option, any later version of Perl 5 you may have available.
665
666
667
668perl v5.28.1                      2016-09-06               WWW::Twilio::API(3)
Impressum