In addition to the Console UI and the Serverless Toolkit, you have the option of directly using the Serverless API to create and manage your Services, Functions, and Assets. This empowers you to create custom build and deployment automations to suit your specific needs.
Functions and Assets created via Functions(Classic) and Assets(Classic) are not available via the API. Similarly, Functions and Assets created via the API aren't available in the Functions(Classic) and Assets(Classic) interface.
Get an overview of the API and the Serverless Toolkit by watching our overview video from Twilio Signal 2019:
Great. Let's have a look at how to deploy a single Function via the API.
First, we'll create a Service, which serves as our container for the environments we set up.
The uniqueName will form part of your domain name, so choose carefully.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createService() {11const service = await client.serverless.v1.services.create({12friendlyName: "testing",13includeCredentials: true,14uniqueName: "demo",15});1617console.log(service.sid);18}1920createService();
1{2"sid": "ZS00000000000000000000000000000000",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"friendly_name": "testing",5"unique_name": "demo",6"include_credentials": true,7"ui_editable": false,8"domain_base": "service-unique-1234",9"date_created": "2018-11-10T20:00:00Z",10"date_updated": "2018-11-10T20:00:00Z",11"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000",12"links": {13"environments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments",14"functions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions",15"assets": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Assets",16"builds": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds"17}18}
We'll get back a Service SID, in the format ZSxxx
.
Next, we'll use that Service SID to create a "dev" Environment.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createEnvironment() {11const environment = await client.serverless.v112.services("ServiceSid")13.environments.create({14domainSuffix: "dev",15uniqueName: "dev-environment",16});1718console.log(environment.sid);19}2021createEnvironment();
1{2"sid": "ZE00000000000000000000000000000000",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ServiceSid",5"build_sid": null,6"unique_name": "dev-environment",7"domain_suffix": "dev",8"domain_name": "foobar-1234-stage.twil.io",9"custom_domain_name": null,10"date_created": "2018-11-10T20:00:00Z",11"date_updated": "2018-11-10T20:00:00Z",12"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000",13"links": {14"variables": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables",15"deployments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Deployments",16"logs": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Logs"17}18}
This will give us an empty environment, e.g. demo-X4HX-dev.twil.io
. To see the domain name for your environment, you can fetch your environment using the ZExxx
SID output from the prior code sample.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function fetchEnvironment() {11const environment = await client.serverless.v112.services("ServiceSid")13.environments("ZEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")14.fetch();1516console.log(environment.domainName);17}1819fetchEnvironment();
1{2"sid": "ZEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ServiceSid",5"build_sid": "ZB00000000000000000000000000000000",6"unique_name": "testing-environment",7"domain_suffix": "testing",8"domain_name": "foobar-1234-testing.twil.io",9"custom_domain_name": null,10"date_created": "2018-11-10T20:00:00Z",11"date_updated": "2018-11-10T20:00:00Z",12"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000",13"links": {14"variables": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Variables",15"deployments": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Deployments",16"logs": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Logs"17}18}
Now let's create our Function. We create the Function at the service level, not inside a particular environment (we'll deploy our Function to an environment later on). Also, we only set the name for the Function at this step. We'll choose a path, visibility, and upload the code for the Function in later steps.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createFunction() {11const func = await client.serverless.v112.services("ServiceSid")13.functions.create({ friendlyName: "firstfunc" });1415console.log(func.sid);16}1718createFunction();
1{2"sid": "ZH00000000000000000000000000000000",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ServiceSid",5"friendly_name": "firstfunc",6"date_created": "2018-11-10T20:00:00Z",7"date_updated": "2018-11-10T20:00:00Z",8"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000",9"links": {10"function_versions": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Functions/ZH00000000000000000000000000000000/Versions"11}12}
You will get back a Function SID in the format ZHxxx
. Save this Function SID for the next step, where we'll create a Version for this Function.
With a Function created, we're ready to create our first Version. Versions of Functions or Assets are where you add the path, visibility (public, protected or private), and the file content itself.
First, we need some code upload. Let's write a simple Function that decides the fate of the universe:
1exports.handler = (context, event, callback) => {2const sparedByThanos = Math.random() > 0.5;34callback(null, {5sparedByThanos,6quote: 'You should have gone for the head.'7});8};
Now we have a Function worth uploading. Save this as a file on your computer named firstfunc.js
.
Now we can upload that file. The create API action is not currently represented in the helper libraries, so you have to do a manual file upload in the language of your choice. See an example below using Node.js.
Remember to replace ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Service SID, and ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with the SID of the newly created Function (from this step).
1const fs = require('fs');2// Before running this code, install "form-data" and "axios" using `npm install form-data axios`3const FormData = require('form-data');4const axios = require('axios');56// Provision API Keys at twilio.com/console/runtime/api-keys7// and set the environment variables. See http://twil.io/secure8const apiKey = process.env.TWILIO_API_KEY;9const apiSecret = process.env.TWILIO_API_SECRET;1011const serviceSid = 'ZSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';12const functionSid = 'ZHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';1314const serviceUrl = `https://serverless-upload.twilio.com/v1/Services/${serviceSid}`;15const uploadUrl = `${serviceUrl}/Functions/${functionSid}/Versions`;1617const form = new FormData();18form.append('Path', '/thanos');19form.append('Visibility', 'public');20form.append('Content', fs.createReadStream('firstfunc.js'), {21contentType: 'application/javascript',22});2324// Create a new Function Version25axios26.post(uploadUrl, form, {27auth: {28username: apiKey,29password: apiSecret,30},31headers: form.getHeaders(),32})33.then((response) => {34const newVersionSid = response.data.sid;35console.log(newVersionSid);36});
With the upload complete, you will see a SID logged to your terminal. Save this Version SID for the next step.
Now, we need to create a Build. A Build will compile Function and Asset Versions into a single, deployable package. This build will live in the Twilio cloud, so you just need the Build SID to reference it — there are no files to keep track of.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createBuild() {11const build = await client.serverless.v112.services("ServiceSid")13.builds.create({14functionVersions: ["ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"],15});1617console.log(build.sid);18}1920createBuild();
1{2"sid": "ZB00000000000000000000000000000000",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ServiceSid",5"asset_versions": [6{7"sid": "ZN00000000000000000000000000000000",8"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",9"service_sid": "ZS00000000000000000000000000000000",10"asset_sid": "ZH00000000000000000000000000000000",11"date_created": "2018-11-10T20:00:00Z",12"path": "/asset-path",13"visibility": "PUBLIC"14}15],16"function_versions": [17{18"sid": "ZN00000000000000000000000000000001",19"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",20"service_sid": "ZS00000000000000000000000000000000",21"function_sid": "ZH00000000000000000000000000000001",22"date_created": "2018-11-10T20:00:00Z",23"path": "/function-path",24"visibility": "PUBLIC"25}26],27"dependencies": [28{29"name": "twilio",30"version": "3.29.2"31},32{33"name": "@twilio/runtime-handler",34"version": "1.0.1"35}36],37"runtime": "node18",38"status": "building",39"date_created": "2018-11-10T20:00:00Z",40"date_updated": "2018-11-10T20:00:00Z",41"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000",42"links": {43"build_status": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000/Status"44}45}
You'll receive a result straight away, but note the status
property. We need to wait until the status returns completed
before continuing. The best way to handle the status changes is to poll every second or two. Here is some sample code to get the current status
of a Build:
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function fetchBuild() {11const build = await client.serverless.v112.services("ServiceSid")13.builds("ZBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")14.fetch();1516console.log(build.status);17}1819fetchBuild();
1{2"sid": "ZBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ServiceSid",5"asset_versions": [6{7"sid": "ZN00000000000000000000000000000000",8"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",9"service_sid": "ZS00000000000000000000000000000000",10"asset_sid": "ZH00000000000000000000000000000000",11"date_created": "2018-11-10T20:00:00Z",12"path": "/asset-path",13"visibility": "PUBLIC"14}15],16"function_versions": [17{18"sid": "ZN00000000000000000000000000000001",19"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",20"service_sid": "ZS00000000000000000000000000000000",21"function_sid": "ZH00000000000000000000000000000001",22"date_created": "2018-11-10T20:00:00Z",23"path": "/function-path",24"visibility": "PUBLIC"25}26],27"dependencies": [28{29"name": "twilio",30"version": "3.29.2"31},32{33"name": "@twilio/runtime-handler",34"version": "1.0.1"35}36],37"runtime": "node18",38"status": "building",39"date_created": "2018-11-10T20:00:00Z",40"date_updated": "2018-11-10T20:00:00Z",41"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000",42"links": {43"build_status": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000/Status"44}45}
When the build is completed
, we're ready to deploy!
For the final step, you must associate the Build we just created with the Environment we created earlier in this tutorial. (Remember the Environment SID!) This is called a Deployment.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createDeployment() {11const deployment = await client.serverless.v112.services("ServiceSid")13.environments("ZEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")14.deployments.create({ buildSid: "ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" });1516console.log(deployment.sid);17}1819createDeployment();
1{2"sid": "ZD00000000000000000000000000000000",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ServiceSid",5"environment_sid": "ZEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",6"build_sid": "ZBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",7"date_created": "2018-11-10T20:00:00Z",8"date_updated": "2018-11-10T20:00:00Z",9"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Environments/ZE00000000000000000000000000000000/Deployments/ZD00000000000000000000000000000000"10}
Your Function will now be live and accessible via URL! You can test it out by going to its URL, such as https://demo-X4HX-dev.twil.io/thanos
(be sure to replace demo-X4HX-dev.twil.io
with the unique domain name for your Environment, which you fetched earlier).
When creating a build, you can also specify any dependencies that your code may have.
To do so, include the dependencies
property, which must be a JSON stringified array of package name
s and version
s.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createBuild() {11const build = await client.serverless.v112.services("ServiceSid")13.builds.create({14dependencies: JSON.stringify([{ name: "randomcolor", version: "0.5.4" }]),15functionVersions: ["ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"],16});1718console.log(build.sid);19}2021createBuild();
1{2"sid": "ZB00000000000000000000000000000000",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ServiceSid",5"asset_versions": [6{7"sid": "ZN00000000000000000000000000000000",8"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",9"service_sid": "ZS00000000000000000000000000000000",10"asset_sid": "ZH00000000000000000000000000000000",11"date_created": "2018-11-10T20:00:00Z",12"path": "/asset-path",13"visibility": "PUBLIC"14}15],16"function_versions": [17{18"sid": "ZN00000000000000000000000000000001",19"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",20"service_sid": "ZS00000000000000000000000000000000",21"function_sid": "ZH00000000000000000000000000000001",22"date_created": "2018-11-10T20:00:00Z",23"path": "/function-path",24"visibility": "PUBLIC"25}26],27"dependencies": [28{29"name": "twilio",30"version": "3.29.2"31},32{33"name": "@twilio/runtime-handler",34"version": "1.0.1"35}36],37"runtime": "node18",38"status": "building",39"date_created": "2018-11-10T20:00:00Z",40"date_updated": "2018-11-10T20:00:00Z",41"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000",42"links": {43"build_status": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000/Status"44}45}
The pattern we used above for uploading Functions is exactly the same as it for Assets.
Asset
Asset Version
via a POST
request to the serverless-uploads.twilio.com
domainAssetVersion
SID(s) we want to be a part of the Build, alongside any functionVersions
and dependencies we might need.1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createBuild() {11const build = await client.serverless.v112.services("ServiceSid")13.builds.create({14assetVersions: ["ZNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],15functionVersions: ["ZNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"],16});1718console.log(build.sid);19}2021createBuild();
1{2"sid": "ZB00000000000000000000000000000000",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ServiceSid",5"asset_versions": [6{7"sid": "ZN00000000000000000000000000000000",8"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",9"service_sid": "ZS00000000000000000000000000000000",10"asset_sid": "ZH00000000000000000000000000000000",11"date_created": "2018-11-10T20:00:00Z",12"path": "/asset-path",13"visibility": "PUBLIC"14}15],16"function_versions": [17{18"sid": "ZN00000000000000000000000000000001",19"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",20"service_sid": "ZS00000000000000000000000000000000",21"function_sid": "ZH00000000000000000000000000000001",22"date_created": "2018-11-10T20:00:00Z",23"path": "/function-path",24"visibility": "PUBLIC"25}26],27"dependencies": [28{29"name": "twilio",30"version": "3.29.2"31},32{33"name": "@twilio/runtime-handler",34"version": "1.0.1"35}36],37"runtime": "node18",38"status": "building",39"date_created": "2018-11-10T20:00:00Z",40"date_updated": "2018-11-10T20:00:00Z",41"url": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000",42"links": {43"build_status": "https://serverless.twilio.com/v1/Services/ZS00000000000000000000000000000000/Builds/ZB00000000000000000000000000000000/Status"44}45}
Definitely take a look at the API reference section for all of the API resources below. You might be particularly interested in Variables to allow setting Environment Variables for a given Environment.