Blog Viewer

How to read API response using Google Tag Manager and pass required data to Google Analytics

By Awanish Dubey posted 06-15-2019 02:40 AM

  

Before jumping to the solution, lets quickly understand what is API & its usage.

So, What is API?

API is an interface to access information stored in database/ Data warehouse of 3rd parties

Let’s try to understand it by one example.

Suppose you have travel portal, where you provide flight status to your users. Flight Status gives you access to current flight information, including scheduled, estimated and actual departure/arrival times, equipment type, delay calculations, terminal, gate and baggage carousel.

Now, as all the flight related information would be available in any global distribution system(GDS) or centralized reservation system owned/authorized by any specific company, so, it’s not feasible to access their database directly.

In this case, you can use GDS API. You need to send request to the API using AJAX and the API will send you the response in a JSON or XML format.

Example – API request for flight id 271046927. 
Note - It's just a dummy API url and its response. https:\/\/api.flightstats.com/flex/flightstatus/{protocol}/v2/{format}/flight/status/{...}

{ flightStatus: { flightId: 271046927, carrier: { fs: "AA", iata: "AA", icao: "AAL", name: "American Airlines", phoneNumber: "1-800-433-7300", active: true }, flightNumber: "100", departureAirport: { fs: "JFK", iata: "JFK", icao: "KJFK", faa: "JFK", name: "John F. Kennedy International Airport", street1: "JFK Airport", street2: "", city: "New York", cityCode: "NYC", stateCode: "NY", postalCode: "11430", countryCode: "US", countryName: "United States", regionName: "North America", timeZoneRegionName: "America/New_York", weatherZone: "NYZ076", localTime: "2012-08-09T14:47:31.438", utcOffsetHours: -4, latitude: 40.642335, longitude: -73.78817, elevationFeet: 13, classification: 1, active: true, delayIndexUrl: "https://api.flightstats.com/flex/delayindex/rest/v1/json/airports/JFK?codeType=fs", weatherUrl: "https://api.flightstats.com/flex/weather/rest/v1/json/all/JFK?codeType=fs" }, arrivalAirport: { fs: "LHR", iata: "LHR", icao: "EGLL", name: "Heathrow Airport", city: "London", cityCode: "LON", stateCode: "EN", countryCode: "GB", countryName: "United Kingdom", regionName: "Europe", timeZoneRegionName: "Europe/London", localTime: "2012-08-09T19:47:31.439", utcOffsetHours: 1, latitude: 51.469603, longitude: -0.453566, elevationFeet: 80, classification: 1, active: true, delayIndexUrl: "https://api.flightstats.com/flex/delayindex/rest/v1/json/airports/LHR?codeType=fs", weatherUrl: "https://api.flightstats.com/flex/weather/rest/v1/json/all/LHR?codeType=fs" }, departureDate: { dateLocal: "2012-08-07T18:10:00.000", dateUtc: "2012-08-07T22:10:00.000Z" }, arrivalDate: { dateLocal: "2012-08-08T06:20:00.000", dateUtc: "2012-08-08T05:20:00.000Z" }, status: "L", schedule: { flightType: "J", serviceClasses: "RFJY", restrictions: "" }, operationalTimes: { publishedDeparture: { dateLocal: "2012-08-07T18:10:00.000", dateUtc: "2012-08-07T22:10:00.000Z" }, publishedArrival: { dateLocal: "2012-08-08T06:20:00.000", dateUtc: "2012-08-08T05:20:00.000Z" }, scheduledGateDeparture: { dateLocal: "2012-08-07T18:10:00.000", dateUtc: "2012-08-07T22:10:00.000Z" }, actualGateDeparture: { dateLocal: "2012-08-07T18:05:00.000", dateUtc: "2012-08-07T22:05:00.000Z" }, flightPlanPlannedDeparture: { dateLocal: "2012-08-07T18:54:00.000", dateUtc: "2012-08-07T22:54:00.000Z" }, estimatedRunwayDeparture: { dateLocal: "2012-08-07T18:49:00.000", dateUtc: "2012-08-07T22:49:00.000Z" }, actualRunwayDeparture: { dateLocal: "2012-08-07T18:23:00.000", dateUtc: "2012-08-07T22:23:00.000Z" }, scheduledGateArrival: { dateLocal: "2012-08-08T06:20:00.000", dateUtc: "2012-08-08T05:20:00.000Z" }, estimatedGateArrival: { dateLocal: "2012-08-08T06:07:00.000", dateUtc: "2012-08-08T05:07:00.000Z" }, actualGateArrival: { dateLocal: "2012-08-08T06:09:00.000", dateUtc: "2012-08-08T05:09:00.000Z" }, flightPlanPlannedArrival: { dateLocal: "2012-08-08T06:14:00.000", dateUtc: "2012-08-08T05:14:00.000Z" }, estimatedRunwayArrival: { dateLocal: "2012-08-08T06:07:00.000", dateUtc: "2012-08-08T05:07:00.000Z" }, actualRunwayArrival: { dateLocal: "2012-08-08T06:05:00.000", dateUtc: "2012-08-08T05:05:00.000Z" } }, codeshares: [ { carrier: { fs: "LY", iata: "LY", icao: "ELY", name: "El Al", active: true }, flightNumber: "8051", relationship: "L" }, { carrier: { fs: "IB", iata: "IB", icao: "IBE", name: "Iberia", active: true }, flightNumber: "4218", relationship: "L" }, { carrier: { fs: "BA", iata: "BA", icao: "BAW", name: "British Airways", phoneNumber: "1-800-AIRWAYS", active: true }, flightNumber: "1511", relationship: "L" }, { carrier: { fs: "GF", iata: "GF", icao: "GFA", name: "Gulf Air", active: true }, flightNumber: "6654", relationship: "L" } ], flightDurations: { scheduledBlockMinutes: 430, blockMinutes: 424, scheduledAirMinutes: 380, airMinutes: 402, scheduledTaxiOutMinutes: 44, taxiOutMinutes: 18, scheduledTaxiInMinutes: 6, taxiInMinutes: 4 }, airportResources: { departureTerminal: "8", departureGate: "B3", arrivalTerminal: "3", arrivalGate: "36" }, flightEquipment: { scheduledEquipment: { iata: "777", name: "Boeing 777 Passenger", turboProp: false, jet: true, widebody: true, regional: false }, tailNumber: "N753AN" }, irregularOperations: [ { type: "CANCELLATION", dateUtc: "2013-02-26T23:00:00.000Z", message: "Cancelled due to mechanical issue." }, { type: "REPLACED_BY", relatedFlightId: 24586521, dateUtc: "2013-02-26T23:00:00.000Z", message: "New flight created to replace a cancelled flight." } ], confirmedIncident: { publishedDate: "2013-02-26T23:00:00.000Z", message: "The plan has slid off the runway." }, operatingCarrier: { fs: "AA", iata: "AA", icao: "AAL", name: "American Airlines", phoneNumber: "1-800-433-7300", active: true }, primaryCarrier: { fs: "AA", iata: "AA", icao: "AAL", name: "American Airlines", phoneNumber: "1-800-433-7300", active: true }}   

Like GDS API, there are many API’s managed by different organizations. Let’s learn, how to read Big commerce API’s response and utilize those data.

Case Study – Suppose, you received a requirement to implement enhanced ecommerce tags for the site using big commerce solution.

Do you find it difficult? Probably, No. if the implemented big commerce theme supports GA enhanced ecommerce tracking.

But, what if, it doesn’t support? You will seek developer’s help to pass required information in data Layer. Isn’t?

But what if there is no development support. How to pass product details in the data Layer especially, on the cart page or checkout page which is very risky to modify for the person who doesn’t have experience of doing it.

In such cases, we can read the Big Commerce API’s which contains information of all the products added in cart or customer information and then this data can be utilized as per our need.

BigCommerce has multiple API's for different purpose like Catalog API, Price List API, Store Information API, Cart API, Checkout API, Order transaction API and many more.

https:\/\/yourdomain.com/api/storefront/cart/
https:\/\/yourdomain.com/api/storefront/checkout 
https:\/\/yourdomain.com/api/storefront/orders/{orderid}

These API's response will be in JSON format and you can find a sample response below:

[{
    "id": "abcb21d5-6d0c-4051-aaa4-9f0c3ce4259a",
    "customerId": 0,
    "email": "tes@test.com",
    "currency": {
        "name": "US Dollars",
        "code": "USD",
        "symbol": "$",
        "decimalPlaces": 2
    },
    "isTaxIncluded": false,
    "baseAmount": 29.99,
    "discountAmount": 0,
    "cartAmount": 20.99,
    "coupons": [],
    "discounts": [{
        "id": "ed6e1059-6e07-4242-be77-f5756be6e291",
        "discountedAmount": 9
    }],
    "lineItems": {
        "physicalItems": [{
            "id": "ed6e1059-6e07-4242-be77-f5756be6e291",
            "parentId": null,
            "variantId": 1036,
            "productId": 387,
            "sku": "TE-060-00-0-US",
            "name": " lite",
            "url": "https:\/\/shop.qaror.com\/products\/ lite.html",
            "quantity": 1,
            "brand": "",
            "isTaxable": true,
            "imageUrl": "https:\/\/cdn11.bigcommerce.com\/s-8atiyfebxx\/products\/387\/images\/1029\/PRODUCT- LITE__10904.1539695072.190.285.jpg?c=2",
            "discounts": [{
                "id": 70,
                "discountedAmount": 8.997
            }],
            "discountAmount": 9,
            "couponAmount": 0,
            "listPrice": 29.99,
            "salePrice": 20.99,
            "extendedListPrice": 29.99,
            "extendedSalePrice": 20.99,
            "isShippingRequired": true,
            "type": "physical",
            "giftWrapping": null
        }],
        "digitalItems": [],
        "giftCertificates": [],
        "customItems": []
    },
    "createdTime": "2019-05-02T11:01:24+00:00",
    "updatedTime": "2019-05-02T11:01:38+00:00"
}]


In case, if you are not aware of the API calls, let me explain you that you can find it in the network tab under XHR files. If not, you can ask support team for the help.

post-1-xhr.jpg

Now suppose, you want to grab details of all the items added in the cart like product name, product SKU, product price, product quantity and push it into eCommerce data Layer object, you can use below code.

<script>
var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() {
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
            }
            anHttpRequest.open("GET", aUrl, true);
            anHttpRequest.send(null);
        }
    }
var theurl = 'https:\/\/shop.qaror.com/api/storefront/cart';
var client = new HttpClient();
client.get(theurl, function(response) {
    var response1 = JSON.parse(response);
    var currencyCode = response1[0].currency.code;
    var newCartArray = [];
    for (var i = 0; i < response1[0].lineItems.physicalItems.length; i++) {

        newCartArray.push({
            'name': response1[0].lineItems.physicalItems[i].name,
            'id': response1[0].lineItems.physicalItems[i].sku,
            'brand': "Tech",
            'quantity': response1[0].lineItems.physicalItems[i].quantity,
            'price': response1[0].lineItems.physicalItems[i].extendedListPrice
        })
    }
    dataLayer.push({
        'event': 'checkout',
        'ecommerce': {
            'currencyCode': currencyCode,
            'checkout': {
                'actionField': {
                    'step': '0'
                },
                'products': newCartArray
            }
        }
    });
}); 
</script>

Note:
a) You must update the variable “theurl” with your own api file URL.
b) After JSON parsing, you need to check the array position to grab the exact values i.e. var currencyCode = response1[0].currency.code;

Now once the code is ready. We just need to create custom HTML tag in GTM and paste this code there. Use page path trigger condition, where you want to run this code. 

GTM - Custom HTML Tag

post-1-custom-html-code.jpg

GTM - Trigger Condition

post-1-trigger.jpg


Output - DataLayer Object

post-1-datalayer.jpg

Once the dataLayer is ready, you can easily utilize these datalayer values by creating dataLayer variables and pass the required information to Google Analytics

Hope this post has helped to solve some real time issues.

Please feel free to write your queries in the comment box.

Originally blog posted on - https://qaror.com/blog/implementation/how-to-read-api-using-google-tag-manager.html


#API
#GoogleTagManager

Permalink

Comments

06-27-2019 01:04 PM

Thanks @Garrett Mark Scott for the comment. Yes, reading API through GTM is something very new and interesting. Thanks for sharing the references. Looking forward to crossing paths more!​

06-20-2019 08:45 PM

Thank you for sharing! XHR was really cool and something I have never even heard of. I kept a list of documents that helped better my understanding. Hope these additional references are handy for other members!

References:
Global Distribution System(GDS)
Computer Reservation System(CRS)
Submitting AJAX Forms with jQuery and Flask (video, 13min)
BigCommerce.com
Network Tab / XHR Request (more interesting than it sounds)
What is a XMLHttpRequest(XHR)
Ajax

Extra things I found interesting:
Web Hypertext Application Technology Working Group(WHATWG) 
So Long XMLHttpRequest, Hello fetch()
jQuery AJAX Listener Recipe for GTM

Most Recent Blogs

Log in to see this information

Either the content you're seeking doesn't exist or it requires proper authentication before viewing.