メニュー

Expand
ページを評価:

Function 実行

The Twilio Function runtime environment is lightweight by design to provide developers with all the flexibility they need. Read on to learn about how your code is executed, what variables and tools this environment provides, and ways you could create a valid response.

During Function invocation, the following steps occur:

  1. Environment Bootstrap – The Twilio Function environment is bootstrapped, and any resources your Function code may rely on are quickly initialized.
  2. Handler Execution The Twilio Environment will then execute the exports.handler method that your code defines, and provide the context, event, and callback parameters, in addition to a selection of useful global utility methods.
  3. Response Emitted When your Twilio Function code has completed, your code must call the callback() method in order to emit your response. After executing the callback() method, your Twilio Function execution will be terminated. This includes any asynchronous processes that may still be executing.

ハンドラーメソッド

The handler method is the interface between Twilio Functions and your application logic. You can think of the handler method as the entry point to your application. This is somewhat analogous to a main() function in Java or __init__ in Python.

Twilio Functions will execute your handler method when it is ready to hand off control of execution to your application logic. If your Function Code does not contain a handler method, Twilio Functions will be unable to execute your logic and will emit an HTTP 500 error.

ハンドラー引数

引数 Type 概要
context object 現在の実行環境の情報が含まれます
event object Twilio Functionに渡されたリクエストパラメーターが含まれます
callback function 実行の完了とレスポンスのエミットに使用される関数です
        
        
        
        Twilio Functionのハンドラーメソッドのひな形

        ハンドラーメソッドのひな形

        Twilio Functionのハンドラーメソッドのひな形

        Contextオブジェクト

        Twilio Functions provides the context object as an interface between the current execution environment and the handler method. The context object provides access to helper methods, as well as your Environment Variables.

        ヘルパーメソッド

        The context object provides helper methods that pre-initialize common utilities and clients that you might find useful when building your application. These helper methods extract all their required configuration from Environment Variables.

        Method Type 概要
        getTwilioClient() Twilio RESTヘルパー アカウントのクレデンシャルをFunction内にインクルードしている場合、初期化済みのTwilio RESTヘルパーライブラリーを返します。 もしFunctionでアカウントのクレデンシャルをインクルードしていない場合、このメソッドの呼び出しはエラーとなります。 コード内でこのエラーをキャッチしない場合、HTTP 500レスポンスとなります。
              
              
              
              組み込みのTwilio RESTヘルパーの使用例

              環境変数

              We encourage developers to use Environment Variables to separate their code from configuration. Using Environment Variables ensures that your code is portable, and that simple configuration changes can be made instantly.

              For a more in-depth explanation and examples, refer to the Environment Variables documentation.

                    
                    
                    
                    既定の環境変数にアクセスする方法の例

                    既定の環境変数からRuntimeのドメインを取得する

                    既定の環境変数にアクセスする方法の例
                          
                          
                          
                          環境変数にアクセスする方法の例

                          環境変数を取得する

                          環境変数にアクセスする方法の例

                          Eventオブジェクト

                          The event object contains the request parameters and headers being passed into your Function. Both POST and GET parameters will be collapsed into the same object. For POST requests, you can pass either form encoded parameters or JSON documents; both will be collapsed into the event object.

                          The specific values that you'll be able to access on event are dependent on what context your Function is being used in and what parameters it is receiving. We'll cover some common use cases and general scenarios below, so you can get the most out of event.

                          webhook パラメーター

                          If you have configured your Function to act as the webhook for an action, such as an incoming SMS or phone call, event will contain a very specific set of values related to the phone number in question. These will be values such as event.From, which resolves to the E.164 formatted phone number as a string, event.Body, which returns the text message of an incoming SMS, and many more. For example, an incoming message will result in event having this shape:

                          {
                            "ToCountry": "US",
                            "ToState": "CA",
                            "SmsMessageSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                            "NumMedia": "0",
                            "ToCity": "BOULEVARD",
                            "FromZip": "",
                            "SmsSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                            "FromState": "WA",
                            "SmsStatus": "received",
                            "FromCity": "",
                            "Body": "Ahoy!",
                            "FromCountry": "US",
                            "To": "+15555555555",
                            "ToZip": "91934",
                            "NumSegments": "1",
                            "MessageSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                            "AccountSid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                            "From": "+14444444444",
                            "ApiVersion": "2010-04-01",
                            "request": {
                              "headers": { ... },
                              "cookies": { ... }
                            },
                          }

                          Refer to the dedicated Messaging and Voice Webhook documentation to learn the full list of properties which you can leverage in your Functions.

                          Webhook properties are always in PascalCase; check to make sure that you have capitalized the first letter of commonly used variables, such as From.

                                
                                
                                
                                Example of how to access webhook values by name from the event object in a Function

                                Access webhook values from event

                                Example of how to access webhook values by name from the event object in a Function

                                Parameters from HTTP requests

                                If your Function is being executed in response to an incoming HTTP request, then the contents of event will directly correspond to the request's query parameters and request body (if any).

                                For example, given a Function with the URL of http-7272.twil.io/response and this request:

                                curl -X GET 'https://http-7272.twil.io/response?age=42&firstName=Rick'

                                The resulting event object will be:

                                {
                                  "firstName": "Rick",
                                  "age": "42",
                                  "request": {
                                    "headers": { ... },
                                    "cookies": { ... }
                                  }
                                }

                                Similarly, given a POST request with query parameters, a JSON body, or both such as:

                                curl -L -X POST 'https://http-7272.twil.io/response?age=42&firstName=Rick' \
                                  -H 'Content-Type: application/json' \
                                  --data-raw '{
                                    "color": "orange"
                                  }'

                                the Function of the receiving end will then have access to an event object with these contents:

                                {
                                  "firstName": "Rick",
                                  "age": "42",
                                  "color": "orange",
                                  "request": {
                                    "headers": { ... },
                                    "cookies": { ... }
                                  }
                                }

                                In the case of a POST request, query parameters and any JSON in the body of the request will be merged into the same object. If a property such as age is defined in both parts of the request, the value defined in the JSON body takes precedence and will overwrite the initial value from the query parameters in event.

                                You might have noticed that event also contains a request object with headers and cookies that aren't explicitly part of the request(s). To learn more about this aspect of event and how you can leverage request headers and cookies, refer to the accessing headers and cookies documentation.

                                Parameters from the Run Function Widget

                                Similar to a direct HTTP request, a Run Function widget is invoking a Function, that Function's event will be populated by any arguments specified in the configuration of that particular Run Function widget.

                                Refer to the Use the Run Function widget in Studio example to see what this looks like in practice when combining Functions and Studio Flows.

                                Callback関数

                                When you have finished processing your request, you need to invoke the callback function to emit a response and signal that your Function has completed its execution. The callback method will automatically determine the data type of your response and serialize the output appropriately.

                                You must invoke the callback method when your Function is done processing. Failure to invoke callback will cause your Function to continue running up to the 10-second execution time limit. When your Function reaches the execution time limit, it will be terminated, and a 504 Gateway timeout error will be returned to the client.

                                Callbackと非同期についての制限

                                It is important to note that when the callback function is invoked, it will terminate all execution of your Function. This includes any asynchronous processes you may have kicked off during the execution of your handler method.

                                For this reason, if you are using libraries that are natively asynchronous and/or operate using Promises, you must properly handle this asynchronous behavior. Structure your code to call callback within the correct callback methods, .then chains, or after await in async functions.

                                      
                                      
                                      
                                      非同期HTTPリクエストでcallback()を適切に使用する方法の例

                                      非同期HTTPリクエストで実行を完了する

                                      非同期HTTPリクエストでcallback()を適切に使用する方法の例

                                      Callbackの引数

                                      引数 Type 概要
                                      error string|null Error indicating what problem was encountered during execution. Defining this value (as anything but null or undefined) will result in the client receiving a HTTP 500 response with the provided payload.
                                      response string|object|null Functionによって生成された成功のレスポンスです。 この引数を渡すことでクライアントは、指定された値を含むHTTP 200レスポンスを受信します。

                                      How do I return an error?

                                      If you have encountered an exception in your code or otherwise want to indicate an error state, invoke the callback method with the error object or intended message as a single parameter:

                                      return callback(error);

                                      How do I return a successful response?

                                      To signal success and return a value, pass a falsy value such as null or undefined as the first parameter to callback, and your intended response as the second parameter:

                                      return callback(null, response);

                                      Please note that all samples demonstrate using the return keyword before calling callback. This is to prevent subsequent code from unintentionally running before handler is terminated, or from calling callback multiple times, and is considered a best practice when working with Functions.

                                            
                                            
                                            
                                            HTTP 500エラーでエラーメッセージを返す方法の例

                                            エラーレスポンスを返す

                                            HTTP 500エラーでエラーメッセージを返す方法の例
                                                  
                                                  
                                                  
                                                  空のHTTP 200 OKの返し方の例

                                                  シンプルな成功レスポンス

                                                  空のHTTP 200 OKの返し方の例
                                                        
                                                        
                                                        
                                                        HTTP 200 OKでプレーンテキストを返す例

                                                        プレーンテキストの成功レスポンスを返す

                                                        HTTP 200 OKでプレーンテキストを返す例
                                                              
                                                              
                                                              
                                                              HTTP 200 OKでJSONを返す方法の例

                                                              JSONの成功レスポンスを返す例

                                                              HTTP 200 OKでJSONを返す方法の例

                                                              How do I return TwiML?

                                                              In addition to the standard response types, Functions has built-in support to allow you to quickly generate and return TwiML for your application's needs.

                                                              This is such a common use case that callback directly accepts valid TwiML objects, such as MessagingResponse and VoiceResponse, as the second argument. If you return TwiML in this way, the Runtime environment will automatically convert your response to XML without any extra work required on your part. (Such as stringifying the TwiML and specifying a response content type)

                                                                    
                                                                    
                                                                    
                                                                          
                                                                          
                                                                          

                                                                          Global classes

                                                                          In addition to the values and helpers available through the context, event, and callback parameters, you have access to some globally-scoped helper classes that you can access without needing to import any new Dependencies.

                                                                          Twilio

                                                                          The Twilio class is accessible at any time. This is commonly used to initialize TwiML or Access Tokens for your Function responses. For example:

                                                                          // Initialize TwiML without needing to import Twilio
                                                                          const response = new Twilio.twiml.MessagingResponse();
                                                                          
                                                                          // Similarly for other utilities, such as Access Tokens
                                                                          const AccessToken = Twilio.jwt.AccessToken;
                                                                          const SyncGrant = AccessToken.SyncGrant;​

                                                                          Runtime

                                                                          The Runtime Client is accessible via Runtime, and exposes helper methods for accessing private Assets, other Functions, and the Sync client. For example:

                                                                          const text = Runtime.getAssets()['/my-file.txt'].open();
                                                                          console.log('Your file contents: ' + text);​

                                                                          レスポンスの組み立て

                                                                          In some instances, your Function may need greater control over the response it is going to emit. For those instances, you can use the Twilio Response object that is available in the global scope of your Function by default. No need to import Twilio yourself!

                                                                          By using the Twilio Response object, you will be able to specify the status code, headers, and body of your response. You can begin constructing a custom response by creating a new Twilio Response object, like so:

                                                                          // No need to import Twilio; it is globally available in Functions
                                                                          const response = new Twilio.Response();

                                                                          Twilio Responseメソッド

                                                                          Method リターンタイプ 概要
                                                                          setStatusCode(int) self HTTPレスポンスにステータスコードを設定する
                                                                          setBody(mixed) self Sets the body of the HTTP response. Takes either an object or string. When setting the body to anything other than text, make sure to set the corresponding Content-Type header with appendHeader()
                                                                          appendHeader(string, string) self Adds a header to the HTTP response. The first argument specifies the header name and the second argument the header value
                                                                          setHeaders(object) self Sets all of the headers for the HTTP response. Takes an object mapping the names of the headers to their respective values
                                                                                
                                                                                
                                                                                
                                                                                Twilio Responseを使用してステータスコードを設定する例

                                                                                レスポンスにステータスコードを設定する

                                                                                Twilio Responseを使用してステータスコードを設定する例
                                                                                      
                                                                                      
                                                                                      
                                                                                      Twilio Responseでプレーンテキストのレスポンスを組み立てる例

                                                                                      プレーンテキストのレスポンスを組み立てる

                                                                                      Twilio Responseでプレーンテキストのレスポンスを組み立てる例
                                                                                            
                                                                                            
                                                                                            
                                                                                            Twilio Responseを使用してJSONレスポンスを組み立てる例

                                                                                            JSONレスポンスを組み立てる

                                                                                            Twilio Responseを使用してJSONレスポンスを組み立てる例
                                                                                                  
                                                                                                  
                                                                                                  
                                                                                                  Twilio Responseを使用してヘッダーを設定する例

                                                                                                  ResponseにHTTPヘッダーを設定する

                                                                                                  Twilio Responseを使用してヘッダーを設定する例
                                                                                                        
                                                                                                        
                                                                                                        
                                                                                                        Twilio Responseに複数のヘッダーを設定する例

                                                                                                        Responseに複数のHTTPヘッダーを設定する

                                                                                                        Twilio Responseに複数のヘッダーを設定する例

                                                                                                        関連トピック

                                                                                                        By now, you should have a pretty good idea of what goes into writing a Function. (Although there are plenty of specifics and examples yet to learn)

                                                                                                        The next important step in your journey is to understand the concept of visibility, and how it affects access to and use of your Functions (and Assets)!

                                                                                                        ページを評価:

                                                                                                        ヘルプが必要ですか?

                                                                                                        We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.

                                                                                                              
                                                                                                              
                                                                                                              

                                                                                                              フィードバックくださりありがとうございます!

                                                                                                              Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

                                                                                                              Sending your feedback...
                                                                                                              🎉 Thank you for your feedback!
                                                                                                              Something went wrong. Please try again.

                                                                                                              Thanks for your feedback!

                                                                                                              Refer us and get $10 in 3 simple steps!

                                                                                                              ステップ1

                                                                                                              Get link

                                                                                                              Get a free personal referral link here

                                                                                                              ステップ2:

                                                                                                              Give $10

                                                                                                              Your user signs up and upgrade using link

                                                                                                              ステップ3

                                                                                                              Get $10

                                                                                                              1,250 free SMSes
                                                                                                              OR 1,000 free voice mins
                                                                                                              OR 12,000 chats
                                                                                                              OR more