Check out our High Performance Batch Processing API: Match and Enrich Data Using CSV/TSV Files as Input Data to our APIs Learn More

Consuming an API with the Go Programming Language

by Interzoid Team


Posted on July 23rd, 2019


Golang Code Example for Consuming Demographic Data APIs

Go (a.k.a. Golang) is a programming language typically used in server-side scenarios. It was created at Google to take advantage of multicore processor architectures, advances in networking, and the emergence of Cloud Computing. Its architecture, simplicity, fast build-times, and fast execution make it ideal to build applications that run in distributed environments. This of course also makes it ideal for API-based applications.

The creators of the language, Rob Pike, Robert Griesemer, and Ken Thompson, also helped create the C programming language, Unix, and UTF-8 (the world's most popular encoding scheme). The language's pedigree lended credibility out of the gate and enabled its subsequent successful adoption starting with its first official release in 2012. Its market momentum, compiled executables for a long list of operating systems, static typing, simplicity (including well thought-out package management), and its thriving community has helped it become popular vis-a-vis dated languages such as PHP and Ruby. It also competes successfully against Python and NodeJS, other popular modern server-side languages. It is in heavy use at Google, as parts of Youtube and the Google application itself have been rewritten in the language. Other popular applications such as Docker and Kubernetes are also written in Go, as well as serving as the backbone of many major commercial sites

If you have not yet tried Go, it is easy to download and install at golang.org

In this blog, we will take a look at consuming an API using Go. Naturally, we will be using one of Interzoid's APIs for this example. In order to execute the code, you will have to register to obtain an API key from Interzoid, a quick process which only requires providing and confirming your email address.

In this example, we will use Interzoid's Global Telephone Information API. It simply requires an international telephone number (with country code) along with the API license key as input values, returning demographics about the number. Here are some example results from calling the API.

Golang coding samples for consuming data APIs, international telephone data API example

Here is a walkthrough of the code:

First, after declaring the main package of our program, we import the HTTP client package which we will use to call the API. We will also import a JSON decoder to parse the result from the API, as well as a formatting package to print the results. All three of these packages comes with the standard Go installation.

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

Then, we will create a custom data type that we will use the store the parsed JSON data from the response so we can print it upon completing the API call.

type Payload struct {
    Country     string
    Region      string
    PrimaryCity string
    Language1   string
    Language2   string
    Language3   string
    Mobile      string
    Wealth      string
    Code        string
}

Next, we will declare the main function (where execution begins), declare the variable with the data type created above, and then call the API, storing the returned data from the API in the response variable (which we don't have to declare since Go utilizes inference typing to determine the variable's type).

func main() {
    // Create the struct variable to store the decoded response
    thePayload := Payload{}

    // Call the API
    response, _ := http.Get("https://api.interzoid.com
        /getglobalnumberinfo?license=YOURAPIKEY&intlnumber=+4906979550")

Next, we check to see if there is an HTTP error returned from the API, and if so report it to the console.

if response.StatusCode != 200 {
    // Report any HTTP Errors
    fmt.Println("Error: ", response.Status)

And finally, if there is not an HTTP error, we format the parsed JSON data and print it as a comma-delimited record to the console (of course, we could format it anyway we want at this point, as well as store it in a database, use it to call another API, etc.)

} else {
    // Decode the JSON and print a comma-delimited response,
    // one of many ways to format the response
    _ = json.NewDecoder(response.Body).Decode(&thePayload)

    fmt.Println(
    thePayload.Country + "," +
    thePayload.Region + "," +
    thePayload.PrimaryCity + "," +
    thePayload.Language1 + "," +
    thePayload.Language2 + "," +
    thePayload.Language3 + "," +
    thePayload.Mobile + "," +
    thePayload.Wealth +
    "\r\n")
    }
}

That's it! Calling any other Interzoid APIs (and many other APIs) would be the same, with the only changes being the URL of the API endpoint, the correct input parameters, and whatever logic you want to employ to store or print the resultant data.

Here is the complete code:

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type Payload struct {
    Country     string
    Region      string
    PrimaryCity string
    Language1   string
    Language2   string
    Language3   string
    Mobile      string
    Wealth      string
    Code        string
}

func main() {
    // Create the struct variable to store the decoded response
    thePayload := Payload{}

    // Call the API
    response, _ := http.Get("https://api.interzoid.com
        /getglobalnumberinfo?license=YOURAPIKEY&intlnumber=+4906979550")

    if response.StatusCode != 200 {
        // Report any HTTP Errors
        fmt.Println("Error: ", response.Status)

    } else {
        // Decode the JSON and print a comma-delimited response,
        // one of many ways to format the response
        _ = json.NewDecoder(response.Body).Decode(&thePayload)

        fmt.Println(
        thePayload.Country + "," +
        thePayload.Region + "," +
        thePayload.PrimaryCity + "," +
        thePayload.Language1 + "," +
        thePayload.Language2 + "," +
        thePayload.Language3 + "," +
        thePayload.Mobile + "," +
        thePayload.Wealth +
        "\r\n")
    }
}

High-Performance Batch Processing: Call our APIs with Text Files as Input.
Perform bulk data enrichment using CSV or TSV files.
More...
Available in the AWS Marketplace.
Optionally add usage billing to your AWS account.
More...
See our Snowflake Native Application. Achieve Data Quality built-in to SQL statements.
Identify inconsistent and duplicate data quickly and easily in data tables and files.
More...
Connect Directly to Cloud SQL Databases and Perform Data Quality Analysis
Achieve better, more consistent, more usable data.
More...
Try our Pay-as-you-Go Option
Start increasing the usability and value of your data - start small and grow with success.
More...
Launch Our Entire Data Quality Matching System on an AWS EC2 Instance
Deploy to the instance type of your choice in any AWS data center globally. Start analyzing data and identifying matches across many databases and file types in minutes.
More...
Free Usage Credits
Register for an Interzoid API account and receive free usage credits. Improve the value and usability of your strategic data assets now.
Automate API Integration into Cloud Databases
Run live data quality exception and enhancement reports on major Cloud Data Platforms direct from your browser.
More...
Check out our APIs and SDKs
Easily integrate better data everywhere.
More...
Example API Usage Code on Github
Sample Code for invoking APIs on Interzoid in multiple programming languages
Business Case: Cloud APIs and Cloud Databases
See the business case for API-driven data enhancement - directly within your important datasets
More...
Documentation and Overview
See our documentation site.
More...
Product Newsletter
Receive Interzoid product and technology updates.
More...