Menu

Expand
Rate this page:

The Twilio Go Helper Library

PILOT

This Twilio product is currently in pilot and in active development. If you've identified an issue with the library, please open an issue. If you would like to particulate in the pilot, please sign up for Twilio Insiders twil.io/insider.

The twilio-go helper library lets you write Go code to make HTTP requests to the Twilio API.

This library is open source, so if you find a feature missing or a bug, we encourage you to file an issue or contribute back to the twilio-go project.

Install the Library

The recommended way to install twilio-go is by using Go Modules.

If you already have an initialized project, you can run the command below from your terminal in the project directory to install the library:

go get github.com/twilio/twilio-go

If you are starting from scratch in a new directory, you will first need to create a go.mod file for tracking dependencies such as twilio-go. This is similar to using package.json in a Node.js project or requirements.txt in a Python project. You can read more about mod files in the Go documentation. To create the file, run the following command in your terminal:

go mod init twilio-example

Once the module is initialized, you may run the installation command from above, which will update your go.mod file to include twilio-go.

Test your installation

Try sending yourself an SMS message by pasting the following code example into a sendSms.go file in the same directory where you installed twilio-go. Be sure to update the accountSid, authToken, and from phone number with values from your Twilio account. The to phone number can be your own mobile phone number.

        
        
        

        Save sendSms.go. In your terminal from the same directory, run:

        go run sendSms.go

        After a brief delay, you will receive the text message on your phone.

        It's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check out How to Set Environment Variables for more information.

        Authenticate Client

        package main
        
        import "github.com/twilio/twilio-go"
        
        func main() {
            accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
            authToken := os.Getenv("TWILIO_AUTH_TOKEN")
            client := twilio.NewRestClientWithParams(twilio.RestClientParams{
                Username: accountSid,
                Password: authToken,
            })
        }
        

        While its possible to construct the Twilio RestClient by directly providing the credentials, if you are already storing your credentials as the environment variables TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN, you can simply initialize a NewRestClient with no arguments and it will automatically look for and pull in those environmental variables.

        package main
        
        import "github.com/twilio/twilio-go"
        
        func main() {
            // TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN are automatically
            // retrieved from the environment for you
            client := twilio.NewRestClient()
        }
        

        Similarly, it's possible to leverage a SubAccountSid and automatic environment variable retrieval, you just need to provide the SubAccountSid as the AccountSid for twilio.RestClientParams:

        package main
        
        import "github.com/twilio/twilio-go"
        
        func main() {
            subaccountSid := "ACYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
            client := twilio.NewRestClientWithParams(twilio.RestClientParams{
                AccountSid: subaccountSid,
            })
        }
        

        Lastly, if you want to follow best practices and initialize your client using an API Key and Secret instead of potentially exposing your account's AuthToken, you can follow the below pattern:

        package main
        
        import (
            "os"
        
            "github.com/twilio/twilio-go"
        )
        
        func main() {
            accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
            apiKey := os.Getenv("TWILIO_API_KEY")
            apiSecret := os.Getenv("TWILIO_API_SECRET")
        
            client := twilio.NewRestClientWithParams(twilio.RestClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        }
        

        In the following examples we’re following the best pratice of creating the Twilio client using an API Key and Secret, instead of directly using and potentially exposing your account’s auth token. If you’d like to learn more about API Keys and how to create one, please refer to the API Key documentation.

        Specify a Region and/or Edge

        package main
        
        import (
            "os"
        
            "github.com/twilio/twilio-go"
        )
        
        func main() {
            accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
            apiKey := os.Getenv("TWILIO_API_KEY")
            apiSecret := os.Getenv("TWILIO_API_SECRET")
        
            client := twilio.NewRestClientWithParams(twilio.RestClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            client.SetRegion("au1")
            client.SetEdge("sydney")
        }
        

        This will result in the hostname transforming from api.twilio.com to api.sydney.au1.twilio.com.

        A Twilio client constructed without these parameters will also look for and use the TWILIO_REGION and TWILIO_EDGE variables if defined in the current environment.

        Create a new Record

        package main
        
        import (
            "fmt"
            "os"
        
            "github.com/twilio/twilio-go"
            openapi "github.com/twilio/twilio-go/rest/api/v2010"
        )
        
        func main() {
            accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
            apiKey := os.Getenv("TWILIO_API_KEY")
            apiSecret := os.Getenv("TWILIO_API_SECRET")
            from := os.Getenv("TWILIO_FROM_PHONE_NUMBER")
            to := os.Getenv("TWILIO_TO_PHONE_NUMBER")
        
            client := twilio.NewRestClientWithParams(twilio.RestClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            params := &openapi.CreateCallParams{}
            params.SetTo(to)
            params.SetFrom(from)
            params.SetUrl("http://demo.twilio.com/docs/voice.xml")
        
            resp, err := client.ApiV2010.CreateCall(params)
            if err != nil {
                fmt.Println(err.Error())
                err = nil
            } else {
                fmt.Println("Call Status: " + *resp.Status)
                fmt.Println("Call Sid: " + *resp.Sid)
                fmt.Println("Call Direction: " + *resp.Direction)
            }
        }
        
        Call Status: queued
        Call SID: CA42ed11f93dc08b952027ffbc406d0868
        Call Direction: outbound-api
        

        Get existing Record

        package main
        
        import (
            "fmt"
            "os"
        
            "github.com/twilio/twilio-go"
            openapi "github.com/twilio/twilio-go/rest/api/v2010"
        )
        
        func main() {
            accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
            apiKey := os.Getenv("TWILIO_API_KEY")
            apiSecret := os.Getenv("TWILIO_API_SECRET")
        
            client := twilio.NewRestClientWithParams(twilio.RestClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            params := &openapi.FetchCallParams{}
        
            resp, err := client.ApiV2010.FetchCall("CA42ed11f93dc08b952027ffbc406d0868", params)
            if err != nil {
                fmt.Println(err.Error())
                err = nil
            } else {
                fmt.Println("Call Status: " + *resp.Status)
                fmt.Println("Call Sid: " + *resp.Sid)
                fmt.Println("Call Direction: " + *resp.Direction)
            }
        }
        
        Call To: +14155551212
        Call Status: completed
        Call SID: CA42ed11f93dc08b952027ffbc406d0868
        

        Iterating through records

        Using ListXxx

        package main
        
        import (
            "fmt"
            "os"
        
            "github.com/twilio/twilio-go"
            openapi "github.com/twilio/twilio-go/rest/api/v2010"
        )
        
        func main() {
            accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
            apiKey := os.Getenv("TWILIO_API_KEY")
            apiSecret := os.Getenv("TWILIO_API_SECRET")
            from := os.Getenv("TWILIO_FROM_PHONE_NUMBER")
        
            client := twilio.NewRestClientWithParams(twilio.RestClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            params := &openapi.ListMessageParams{}
            params.SetFrom(from)
            params.SetPageSize(20)
            params.SetLimit(100)
        
            resp, _ := client.ApiV2010.ListMessage(params)
            for record := range resp {
                fmt.Println("Body: ", *resp[record].Body)
            }
        }
        

        Using StreamXxx

        package main
        
        import (
            "fmt"
            "os"
        
            "github.com/twilio/twilio-go"
            openapi "github.com/twilio/twilio-go/rest/api/v2010"
        )
        
        func main() {
            accountSid := os.Getenv("TWILIO_ACCOUNT_SID")
            apiKey := os.Getenv("TWILIO_API_KEY")
            apiSecret := os.Getenv("TWILIO_API_SECRET")
            from := os.Getenv("TWILIO_FROM_PHONE_NUMBER")
        
            client := twilio.NewRestClientWithParams(twilio.RestClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            params := &openapi.ListMessageParams{}
            params.SetFrom(from)
            params.SetPageSize(20)
            params.SetLimit(100)
        
            channel, _ := client.ApiV2010.StreamMessage(params)
            for record := range channel {
                fmt.Println("Body: ", *record.Body)
            }
        }
        

        The library automatically handles paging for you. Collections, such as calls and messages, have ListXxx and StreamXxx methods that page under the hood. With both ListXxx and StreamXxx, you can specify the number of records you want to receive (limit) and the maximum size you want each page fetch to be (pageSize). The library will then handle the task for you.

        ListXxx eagerly fetches all records and returns them as a list, whereas SteamXxx streams records and lazily retrieves pages of records as you iterate over the collection. You can also page manually using the PageXxx method.

        Handling Exceptions

        If the Twilio API returns a 400 or a 500 level HTTP response, the twilio-go library will include information in the returned err value. 400-level errors are normal during API operation ("Invalid number", "Cannot deliver SMS to that number", for example) and should be handled appropriately.

        Getting Help

        We'd love to hear your feedback on the Twilio Go Helper Library and help you past any issues you may encounter. Feel free to drop us a line, and we'll make sure to get you sorted!

        Rate this page:

        Need some help?

        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 Community Forums or browsing the Twilio tag on Stack Overflow.

        Thank you for your feedback!

        We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

        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!

        Step 1

        Get link

        Get a free personal referral link here

        Step 2

        Give $10

        Your user signs up and upgrade using link

        Step 3

        Get $10

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