Once you have an access token you can make HTTP requests to the API. API tokens expire in 1 hour from their creation.
Each API request will be made to a different URL in the API.
All API requests will include the same header information:
- Content-Type => application/json,
- Accept => application/json,
- Authorization => Bearer AccessTokenThatYouCopied
POST and PATCH requests will generally require a JSON formatted body be passed in the request.
GET Example with MATLAB
Continuing from the MATLAB example above to get the the Access token
%% Setup the options to do the various gets
options = weboptions('RequestMethod','get',...
'ContentType','json',...
'KeyName','Authorization',...
'KeyValue',['Bearer ',tokenRequestResponse.access_token]);
disp('');
disp('The options I need to pass for GET requests');
disp(options);
%% Get the sites i have in my account
disp('The sites I have in my account');
data= webread(...
'https://tqa.imageowl.com/api/rest/sites',...
'Accept','application/json',...
options);
tblSites = struct2table(data.sites)
%% What are the machine IDs associated with the first site in my account?
disp('What are the machine IDs associated with the first site in my account?');
firstID = data.sites(1).id;
machineData = webread(...
['https://tqa.imageowl.com/api/rest/machines?site=',int2str(firstID)],...
'Accept','application/json',...
options);
tblMachine = struct2table(machineData.machines,'AsArray',true)
GET Example with Python
A more complete example building on the Python example above that includes a GET call.
import json
import requests
class tqa_Connect:
def demo(self):
payload = {"client_id": "Your API Label",
"client_secret": "Your API Key",
"grant_type": "client_credentials"
}
r = requests.post('https://tqa.imageowl.com/api/rest/oauth',data = payload)
print 'Status Code:',r.status_code
j = r.json()
accessToken = j['access_token']
print 'Access Token: ',j['access_token']
bearerToken = 'Bearer ' + accessToken
url = "https://tqa.imageowl.com/api/rest/sites"
headers = {
'authorization': bearerToken,
'content-type': "application/json",
'accept': "application/json",
}
response = requests.request("GET", url, headers=headers)
print json.dumps(response.json(), indent=4, sort_keys=True)
tqa_Connect().demo()
GET Example with R
A more complete example building on the R example above that includes a GET call.
library(httr)
url <- 'http://tqa.imageowl.com/api/rest/oauth'
body <- list(client_id = 'Your API Label', client_secret= 'Your API Key',grant_type = 'client_credentials')
# get the access token in a respone
r <- POST(url, body = body, encode = "form")
tqa_token <- content(r,"parsed")
authorization <- paste('Bearer',tqa_token$access_token)
accept <- 'application/json'
tqa_headers <- c(Authorization= authorization,Accept = accept)
siteUrl <- 'https://tqa.imageowl.com/api/rest/sites'
s <- GET(siteUrl,add_headers(.headers = tqa_headers))
sites <- content(s,"parsed")
str(sites)
GET Example with C#
A complete example building on the C# example above that includes a GET call.
A utility class to hold the site information when it is returned.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
namespace TQA_API_Demo
{
[DataContract]
public class Site
{
[DataMember(Name= "id")]
public int ID { get; set; }
[DataMember(Name= "name")]
public String Name { get; set; }
[DataMember(Name= "notes")]
public String Notes { get; set; }
[DataMember(Name = "ownerId")]
public int OwnerID { get; set; }
[DataMember(Name = "machineIds")]
public List<int> MachineIds { get; set; }
[DataMember(Name = "userIds")]
public List<int> UserIds { get; set; }
}
[DataContract]
public class SiteList
{
[DataMember(Name = "sites")]
public List<Site> Sites { get; set; }
}
}
And now we use the access token to get the site information
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json; // uses the Json.NET assembly a freely available JSON library
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
namespace TQA_API_Demo
{
class Program
{
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
// TODO - Send HTTP requests
Uri baseAddress = new Uri("https://tqadev.imageowl.com/");
client.BaseAddress = baseAddress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var accessRequestData = new AccessRequest()
{
ClientID = "141:Webinar",
ClientSecret = "42d1a2b2277bbafc906b2a60744f2fb231757cef06df6e231a779093000b3e03",
GrantType = "client_credentials"
};
//HTTP get the access token
HttpResponseMessage response = await client.PostAsJsonAsync("api/rest/oauth", accessRequestData);
if (response.IsSuccessStatusCode)
{
accessRequestResponseData responseData = await response.Content.ReadAsAsync<accessRequestResponseData>();
Console.WriteLine("{0}\t{1}",responseData.AccessToken,responseData.ExpiresIn);
//Now that we have the access code let's get some data about the sites
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "api/rest/sites");
requestMessage.Headers.Add("Authorization", "Bearer " + responseData.AccessToken);
response = await client.SendAsync(requestMessage);
string responseAsString = await response.Content.ReadAsStringAsync();
//prettify
Console.WriteLine(FormatJSON(responseAsString));
//turn the response into a list of Site objects
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(SiteList));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(responseAsString));
var obj = (SiteList)ser.ReadObject(stream);
Console.WriteLine("ID\tName\tMachine Ids\tUser Ids");
foreach (Site s in obj.Sites)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}",
s.ID,
s.Name,
string.Join(",", s.MachineIds.ToArray()),
string.Join(",", s.UserIds.ToArray()));
}
}
Console.ReadLine();
}
}
private static string FormatJSON(string json)
{
dynamic parsedJson = JsonConvert.DeserializeObject(json);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
}
}