How to make REST API requests in PowerShell
To make an HTTP request to Twilio's API from PowerShell, use the Invoke-WebRequest cmdlet with HTTP Basic Authentication to send an SMS message.
PowerShell allows developers to write command line scripts using the full power of the .NET framework. However, some tasks you may be used to performing in *nix environments, like making an authenticated HTTP request with curl, are not as straightforward.
The following example script sends an SMS message:
1# Complete example: Send an SMS with Twilio from PowerShell2# Pull in Twilio account info, previously set as environment variables3$sid = $env:TWILIO_ACCOUNT_SID4$apiKey = $env:TWILIO_API_KEY5$apiSecret = $env:TWILIO_API_SECRET6$number = $env:TWILIO_NUMBER78# Twilio API endpoint and POST params9$url = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json"10$params = @{ To = "+15558675309"; From = $number; Body = "Hello from PowerShell" }1112# Create a credential object for HTTP basic auth13$p = $apiSecret | ConvertTo-SecureString -asPlainText -Force14$credential = New-Object System.Management.Automation.PSCredential($apiKey, $p)1516# Make API request, selecting JSON properties from the response17Invoke-WebRequest $url -Method Post -Credential $credential -Body $params -UseBasicParsing |18ConvertFrom-Json | Select sid, body
Let's break down the moving parts of this script.
Set up the credentials and phone number your Twilio account needs before making API requests.
First, export the Twilio account credentials and phone number you need to send an outbound SMS. Find your Account SID and create an API key on your Console dashboard. You can use an existing phone number or buy one in the Console.
There are a number of ways to configure system environment variables on Windows, but you can set user-level environment variables in PowerShell with the following commands. Replace the strings below with the relevant values from your account.
1[Environment]::SetEnvironmentVariable("TWILIO_ACCOUNT_SID", "your_account_sid", "User")2[Environment]::SetEnvironmentVariable("TWILIO_API_KEY", "your_api_key", "User")3[Environment]::SetEnvironmentVariable("TWILIO_API_SECRET", "your_api_secret", "User")4[Environment]::SetEnvironmentVariable("TWILIO_NUMBER", "+16518675309", "User")
In the example script at the beginning of the article, we access these variables through the $env variable.
1$sid = $env:TWILIO_ACCOUNT_SID2$apiKey = $env:TWILIO_API_KEY3$apiSecret = $env:TWILIO_API_SECRET4$number = $env:TWILIO_NUMBER
Build the endpoint URL for the Messages resource, then define the parameters to send with the request.
$url = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json"
Breaking down the URL:
https://api.twilio.com: The Twilio API base domain2010-04-01: The Twilio REST API version. This is a stable API version maintained by Twilio. For other endpoints or latest API information, see the Messaging API Reference.Accounts/$sid: Your Twilio Account SID (the variable substitution makes this dynamic)Messages.json: The endpoint for sending SMS messages, with.jsonextension to specify JavaScript Object Notation (JSON) response format
Different Twilio products use different endpoints. For example:
- SMS/Messages:
/Accounts/{AccountSid}/Messages.json - Calls:
/Accounts/{AccountSid}/Calls.json - Phone Numbers:
/Accounts/{AccountSid}/IncomingPhoneNumbers.json
For the complete list of available endpoints for your use case, refer to the individual resource reference pages (for example, Messaging API, Voice API, Phone Number Management).
Next, we create a hash table with the POST parameters we need to send with our request.
$params = @{ To = "+15558675309"; From = $number; Body = "Hello from PowerShell" }
Purpose of each parameter
To: The phone number to send the SMS to (replace+15558675309with the actual recipient's phone number in E.164 format)From: A Twilio-powered phone number the SMS message will come from (this comes from your$numberenvironment variable)Body: The actual text of the outbound message
Next, create a PSCredential object to pass your HTTP Basic Authentication credentials to Twilio. We need to create a PSCredential to pass into the Invoke-WebRequest command.
1$p = $apiSecret | ConvertTo-SecureString -asPlainText -Force2$credential = New-Object System.Management.Automation.PSCredential($apiKey, $p)
Now that we have all our configuration ready, we use the Invoke-WebRequest command to send the SMS. The script uses the ConvertFrom-Json command to parse the JSON response from the Twilio API and the Select command to extract specific properties.
For PowerShell 5.1 and earlier, include -UseBasicParsing to prevent creating a Document Object Model (DOM) from the results and to avoid errors on systems without Internet Explorer installed. In PowerShell 6.0 and later, this flag is ignored.
1Invoke-WebRequest $url -Method Post -Credential $credential -Body $params -UseBasicParsing |2ConvertFrom-Json | Select sid, body
Complete script:
1# Pull in Twilio account info, previously set as environment variables2$sid = $env:TWILIO_ACCOUNT_SID3$apiKey = $env:TWILIO_API_KEY4$apiSecret = $env:TWILIO_API_SECRET5$number = $env:TWILIO_NUMBER67# Twilio API endpoint and POST params8$url = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json"9$params = @{ To = "+15558675309"; From = $number; Body = "Hello from PowerShell" }1011# Create a credential object for HTTP basic auth12$p = $apiSecret | ConvertTo-SecureString -asPlainText -Force13$credential = New-Object System.Management.Automation.PSCredential($apiKey, $p)1415# Make API request, selecting JSON properties from the response16Invoke-WebRequest $url -Method Post -Credential $credential -Body $params -UseBasicParsing |17ConvertFrom-Json | Select sid, body
When running this script, you may encounter common errors. Here are solutions to resolve them:
| Issue | Cause | Solution |
|---|---|---|
The variable '$env:TWILIO_ACCOUNT_SID' cannot be retrieved because it has not been set. | Environment variable not set | Run the SetEnvironmentVariable commands from the Export system environment variables section, then restart PowerShell for the changes to take effect. Alternatively, set the variable directly in the current session with $env:TWILIO_ACCOUNT_SID = "your_account_sid". |
The remote server returned an error: (401) Unauthorized. | Invalid credentials | Verify your TWILIO_API_KEY, TWILIO_ACCOUNT_SID, and TWILIO_API_SECRET environment variables match your Console credentials. Regenerate your API key if needed. |
| Error 21211: Invalid 'To' Phone Number | Invalid phone number format | Ensure the To parameter uses E.164 format (for example, +15551234567). The first + is required, followed by country code and number. |
ConvertFrom-Json error | Response is not valid JSON | Store the response and inspect it: $response = Invoke-WebRequest $url -Method Post -Credential $credential -Body $params ; $response.Content | ConvertFrom-Json -ErrorAction Stop to see detailed error messages. |
With this code, you can make an authenticated REST API request from PowerShell and send an SMS message without leaving the shell.
For additional guidance and examples:
- Send Your First SMS: Get started with our SMS quickstart guide.
- Twilio Messaging API Reference: Explore all available Twilio messaging endpoints.
- Create an API Key: Manage your authentication credentials.
- PowerShell documentation: Learn more about PowerShell scripting.