Code Samples (PHP, Javascript & Python)

Here are some samples of code you can use to query AT Internet Rest API. Please note that you need AT Internet credentials to login.

Please refer to this note if you’re using SSO to login to AT Internet services.
 

PHP script (json format)

<?php
// configuration of the Rest API
$site 			= '554331';
$results 		= '50';
$page 			= '1';
$credentials 	= 'email@email.com:password';
$api			= "https://apirest.atinternet-solutions.com/data/v2/json/getData?&columns={d_source,d_page,d_l2,m_visits,m_page_loads}&sort={-m_visits}&filter={d_l2:{\$empty:false}}&space={s:".$site."}&period={R:{D:'-1'}}&max-results=".$results."&page-num=".$page;

// Configuration of the API Headers
$headers = array(
	"Authorization: Basic " . base64_encode($credentials)
); 

// Connection to the AT Internet API
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$api);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($curl_handle, CURLOPT_TIMEOUT, 60); 

// $query is the JSON Response
$query = json_decode(curl_exec($curl_handle),true);
curl_close($curl_handle);

// Function to parse the JSON and display a nice HTML table
function readATInternetApi($a) {
	$return = '<table>';
	$return .= '<tr>';
	foreach($a["DataFeed"][0]["Columns"] as $col){
		$return .= "<td>".$col["Label"]."</td>";
	}
	$return .= '</tr>';
	foreach($a["DataFeed"][0]["Rows"] as $row){
		$return .= '<tr>';
		foreach($a["DataFeed"][0]["Columns"] as $col){
			$return .= '<td>'.$row[$col["Name"]].'</td>';
		}
		$return .= '<tr>';
	}
	$return .= '</table>';
	echo $return;
}

// Execution of the function to show the HTML table
readATInternetApi($query);
?>
 

PHP script (xml format)

<?php
// configuration of the Rest API
$site 			= '554331';
$results 		= '50';
$page 			= '1';
$credentials 	= 'email@email.com:password';
$api			= "https://apirest.atinternet-solutions.com/data/v2/xml/getData?&columns={d_source,d_page,d_l2,m_visits,m_page_loads}&sort={-m_visits}&filter={d_l2:{\$empty:false}}&space={s:".$site."}&period={R:{D:'-1'}}&max-results=".$results."&page-num=".$page;

// Configuration of the API Headers
$headers = array(
	"Authorization: Basic " . base64_encode($credentials)
); 

// Connection to the AT Internet API
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$api);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($curl_handle, CURLOPT_TIMEOUT, 60); 

// $query is the JSON Response
$query = simplexml_load_string(curl_exec($curl_handle));
curl_close($curl_handle);

// Function to parse the JSON and display a nice HTML table
function readATInternetApi($a) {
	$return = '<table>';
	$return .= '<tr>';
	foreach($a->DataSet->Columns->Column as $col){
		$return .= "<td>".$col["Label"]."</td>";
	}
	$return .= '</tr>';
	foreach($a->DataSet->Rows->Row as $row){
		$return .= '<tr>';
		foreach($a->DataSet->Columns->Column as $col){
			$return .= '<td>'.$row[$col["Name"]].'</td>';
		}
		$return .= '<tr>';
	}
	$return .= '</table>';
	echo $return;
}

// Execution of the function to show the HTML table
readATInternetApi($query);
?>
 

JavaScript (json format)

<html>
  <head>
    <meta charset="utf-8">
    <title>Use API with javascript</title>
  </head>
  <body>
	<div id="result"></div>
  </body>
  <!-- JQuery library -->
  <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>

  <script>
	// Set up
	var user       = 'email@email.com';
	var password   = 'password';
	var site       = '554331';
	var maxResults = '50';
	var pageNum    = '1'
	
	var url = "https://apirest.atinternet-solutions.com/data/v2/json/getData?&columns={d_source,d_page,d_l2,m_visits,m_page_loads}&sort={-m_visits}&filter={d_l2:{$empty:false}}&space={s:"+site+"}&period={R:{D:'-1'}}&max-results="+maxResults+"&page-num="+pageNum+"";
	
	// AJAX request with JQuery to call the AT Internet API
	$.ajax({
		xhrFields: {
			withCredentials: false
		},
		headers: {
			'Authorization': 'Basic ' + btoa(user+':'+password)
		},
		url: url,
		success: function(data){
			readATInternetApi(data);
		},
		error: function(){
			$('#result').append('<h2>Oops something went wrong :( Please check the parameters.</h2>');
		}
	});
	
	<!-- Function that parses the JSON object to display a HTML table-->
	function readATInternetApi(data){
		var res = '<table>';
		res += '<tr>';
	
		var dColums = data.DataFeed["0"]["Columns"]; // data stored in 'Columns' field
		var dRow 	= data.DataFeed["0"]["Rows"] // data stored in 'Rows' field
		
		for(var property in dColums){
			if (dColums.hasOwnProperty(property)){
				res += "<th>"+dColums[property]["Label"]+"</th>";
			}
		}
		res += '</tr>';
		
		for(var row in dRow){
			if (dRow.hasOwnProperty(row)){
				res += '<tr>';
				for(var col in dColums){
					if (dColums.hasOwnProperty(col)) {
						res += '<td>'+dRow[row][dColums[col]["Name"]]+'</td>';
					}
				}
				res += '</tr>';
			}
		}
		res += '</table>';
		$('#result').append(res);
	}
</script>
</html>
 

Python script (json format)

# coding : utf-8
import requests
import codecs

url = "https://apirest.atinternet-solutions.com/data/v2/json/getData"

# You have to encode your credentials using base64 to generate a unique key: email@email.com:password
headers = {
    'authorization': "Basic amVyZW15LmNhc3RhbkBhdGludGVybmV0LmNvbTptYXJjbGVib2dvc3M="
    }

nb_results = 50
file = codecs.open("C:\\Users\\YOUR_USER_NAME\\Desktop\\MyRawData.txt","w",encoding='utf8')

for page in range(1,5):
	querystring = {"columns":"{d_source,m_visits}","sort":"{-m_visits}","space":'{s:123456}',"period":"{R:{D:'-1'}}","max-results":"%d" % nb_results,"page-num":"%d" % page} 
	response = requests.request("GET", url, headers=headers, params=querystring)
	file.write(response.text)

file.close()
 

R script

##Packages setup#
install.packages("httr")
install.packages("RCurl")
require(httr)
require(RCurl)

## Function to count the number of required calls
rcall<-function(URL,user,password){
  CallRaw<-paste("https://apirest.atinternet-solutions.com/data/v2/json/getRowCount?",URL,sep="")
  NumRow<-content(GET(CallRaw,config=authenticate(user,password,"basic")))
  Page<-floor(NumRow$RowCounts[[1]]$RowCount/10000)+1
  URL<-paste("https://apirest.atinternet-solutions.com/data/v2/json/getData?",URL,"&max-results=10000&page-num=",sep="")
  DfCall<-as.data.frame(matrix(NA),nrow=Page)
  for(i in 1:Page){
    DfCall[i,]<-paste(URL,i,sep="")
  }
  return (DfCall)
}

Result<-function(DfCall,user,password){
  
  Result<-as.data.frame(matrix(NA,ncol=2))
  
  for(i in 1:nrow(DfCall)){
    
    #API call execution
    APIResults<-content(GET(DfCall[i,],config=authenticate(user,password,"basic")))
    #Storage of the results in a data frame
    Result2<-do.call(rbind, lapply(APIResults$DataFeed[[1]]$Rows, data.frame, stringsAsFactors=FALSE))
    #Columns Setups
    colnames(Result)<-colnames(Result2)
    #Binding of the results
    Result<-rbind(Result,Result2)
    print(paste("Call to page ",i," has been successfully completed"))
  }
  
  return(Result)
}

#Call Sample

email="TO BE FILLED IN"
password="TO BE FILLED IN"

Test<-rcall("&columns={d_source_global,m_visits}&sort={-m_visits}&space={s:123123}&period={M:'2017-06'}",email,password)

Result(Test,email,password)
 

Was this post helpful?

Last update: 22/01/2019