Menu

The Twilio Go Helper Library

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.

        Using this Library

        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.ClientParams{
                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.ClientParams:

        package main
        
        import "github.com/twilio/twilio-go"
        
        func main() {
            subaccountSid := "ACYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
            client := twilio.NewRestClientWithParams(twilio.ClientParams{
                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.ClientParams{
                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.ClientParams{
                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 Call

        package main
        
        import (
            "fmt"
            "os"
        
            "github.com/twilio/twilio-go"
            twilioApi "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.ClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            params := &twilioApi.CreateCallParams{}
            params.SetTo(to)
            params.SetFrom(from)
            params.SetUrl("http://demo.twilio.com/docs/voice.xml")
        
            resp, err := client.Api.CreateCall(params)
            if err != nil {
                fmt.Println(err.Error())
            } 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 data about an existing Call

        package main
        
        import (
            "fmt"
            "os"
        
            "github.com/twilio/twilio-go"
            twilioApi "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.ClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            params := &twilioApi.FetchCallParams{}
        
            resp, err := client.Api.FetchCall("CA42ed11f93dc08b952027ffbc406d0868", params)
            if err != nil {
                fmt.Println(err.Error())
            } 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"
            twilioApi "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.ClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            params := &twilioApi.ListMessageParams{}
            params.SetFrom(from)
            params.SetPageSize(20)
            params.SetLimit(100)
        
            resp, _ := client.Api.ListMessage(params)
            for record := range resp {
                fmt.Println("Body: ", *resp[record].Body)
            }
        }
        

        Using StreamXxx

        package main
        
        import (
            "fmt"
            "os"
        
            "github.com/twilio/twilio-go"
            twilioApi "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.ClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            params := &twilioApi.ListMessageParams{}
            params.SetFrom(from)
            params.SetPageSize(20)
            params.SetLimit(100)
        
            channel, _ := client.Api.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. Also, List returns no records if any errors are encountered while paging, whereas Stream returns all records up until encountering an error. You can also page manually using the PageXxx method.

        Using PageXxx

        package main
        
        import (
            "fmt"
            "os"
        
            "github.com/twilio/twilio-go"
            twilioApi "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.ClientParams{
                Username:   apiKey,
                Password:   apiSecret,
                AccountSid: accountSid,
            })
        
            params := &twilioApi.ListMessageParams{}
            params.SetFrom(from)
            params.SetPageSize(20)
        
            var pageToken string
            var pageNumber string
            resp, err = client.Api.PageMessage(params, "", "")
            if err != nil {
                fmt.Println(err)
            } else {
                fmt.Println(resp.NextPageUri)
                u, _ := url.Parse(resp.NextPageUri)
                q := u.Query()
                pageToken = q.Get("PageToken")
                pageNumber = q.Get("Page")
            }
        
            resp, err := client.Api.PageMessage(params, pageToken, pageNumber)
            if err != nil {
                fmt.Println(err)
            } else {
                if resp != nil {
                    fmt.Println(*resp.Messages[0].Body)
                }
            }
        }
        

        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.

        package main
        
        import (
            "fmt"
            "os"
        
            "github.com/twilio/twilio-go"
            twilioclient "github.com/twilio/twilio-go/client"
            twilioApi "github.com/twilio/twilio-go/rest/api/v2010"
        )
        
        func main() {
            phoneNumber := os.Getenv("TWILIO_PHONE_NUMBER")
        
            client := twilio.NewRestClient()
        
            params := &twilioApi.CreateIncomingPhoneNumberParams{}
            params.SetPhoneNumber(phoneNumber)
        
            resp, err := client.Api.CreateIncomingPhoneNumber(params)
            if err != nil {
                twilioError := err.(*twilioclient.TwilioRestError)
                fmt.Println(twilioError.Error())
            }
        }
        

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

        Thank you for your feedback!

        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!

        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