Skip to contentSkip to navigationSkip to topbar
Page tools
Useful for sharing or LLM
Accelerate development with AI

On this page
Looking for more inspiration?Visit the

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(link takes you to an external page) 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:

Send an SMS with Twilio

send-an-sms-with-twilio page anchor
1
# Complete example: Send an SMS with Twilio from PowerShell
2
# Pull in Twilio account info, previously set as environment variables
3
$sid = $env:TWILIO_ACCOUNT_SID
4
$apiKey = $env:TWILIO_API_KEY
5
$apiSecret = $env:TWILIO_API_SECRET
6
$number = $env:TWILIO_NUMBER
7
8
# Twilio API endpoint and POST params
9
$url = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json"
10
$params = @{ To = "+15558675309"; From = $number; Body = "Hello from PowerShell" }
11
12
# Create a credential object for HTTP basic auth
13
$p = $apiSecret | ConvertTo-SecureString -asPlainText -Force
14
$credential = New-Object System.Management.Automation.PSCredential($apiKey, $p)
15
16
# Make API request, selecting JSON properties from the response
17
Invoke-WebRequest $url -Method Post -Credential $credential -Body $params -UseBasicParsing |
18
ConvertFrom-Json | Select sid, body

Let's break down the moving parts of this script.


Export system environment variables

export-system-environment-variables page anchor

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.

Set Twilio credentials as environment variables

set-twilio-credentials-as-environment-variables page anchor
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.

Pull environment variables into script

pull-environment-variables-into-script page anchor
1
$sid = $env:TWILIO_ACCOUNT_SID
2
$apiKey = $env:TWILIO_API_KEY
3
$apiSecret = $env:TWILIO_API_SECRET
4
$number = $env:TWILIO_NUMBER

Configure REST API endpoint and credentials

configure-rest-api-endpoint-and-credentials page anchor

Build the endpoint URL for the Messages resource, then define the parameters to send with the request.

Configure the API endpoint URL

configure-the-api-endpoint-url page anchor
$url = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json"

Breaking down the URL:

  • https://api.twilio.com: The Twilio API base domain
  • 2010-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 .json extension 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(link takes you to an external page) with the POST parameters we need to send with our request.

Define the SMS message parameters

define-the-sms-message-parameters page anchor
$params = @{ To = "+15558675309"; From = $number; Body = "Hello from PowerShell" }

Purpose of each parameter

  • To: The phone number to send the SMS to (replace +15558675309 with 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 $number environment 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(link takes you to an external page) to pass into the Invoke-WebRequest command.

Create HTTP basic authentication credentials

create-http-basic-authentication-credentials page anchor
1
$p = $apiSecret | ConvertTo-SecureString -asPlainText -Force
2
$credential = New-Object System.Management.Automation.PSCredential($apiKey, $p)

Make an authenticated API request in PowerShell

make-an-authenticated-api-request-in-powershell page anchor

Now that we have all our configuration ready, we use the Invoke-WebRequest(link takes you to an external page) command to send the SMS. The script uses the ConvertFrom-Json(link takes you to an external page) command to parse the JSON response from the Twilio API and the Select(link takes you to an external page) 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.

Send the API request and parse the JSON response

send-the-api-request-and-parse-the-json-response page anchor
1
Invoke-WebRequest $url -Method Post -Credential $credential -Body $params -UseBasicParsing |
2
ConvertFrom-Json | Select sid, body

Complete script:

Complete example: Send an SMS from PowerShell

complete-example-send-an-sms-from-powershell page anchor
1
# Pull in Twilio account info, previously set as environment variables
2
$sid = $env:TWILIO_ACCOUNT_SID
3
$apiKey = $env:TWILIO_API_KEY
4
$apiSecret = $env:TWILIO_API_SECRET
5
$number = $env:TWILIO_NUMBER
6
7
# Twilio API endpoint and POST params
8
$url = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json"
9
$params = @{ To = "+15558675309"; From = $number; Body = "Hello from PowerShell" }
10
11
# Create a credential object for HTTP basic auth
12
$p = $apiSecret | ConvertTo-SecureString -asPlainText -Force
13
$credential = New-Object System.Management.Automation.PSCredential($apiKey, $p)
14
15
# Make API request, selecting JSON properties from the response
16
Invoke-WebRequest $url -Method Post -Credential $credential -Body $params -UseBasicParsing |
17
ConvertFrom-Json | Select sid, body

Troubleshooting common issues

troubleshooting-common-issues page anchor

When running this script, you may encounter common errors. Here are solutions to resolve them:

IssueCauseSolution
The variable '$env:TWILIO_ACCOUNT_SID' cannot be retrieved because it has not been set.Environment variable not setRun 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 credentialsVerify 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 NumberInvalid phone number formatEnsure the To parameter uses E.164 format (for example, +15551234567). The first + is required, followed by country code and number.
ConvertFrom-Json errorResponse is not valid JSONStore 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: