Problem
How do I search for a Client/s (end-user/s) under my Partner account using the Partner API?
Searching (API GET) for client/s using the RESTful Partner API based on a specified criteria
Solution
The following example of code shows you how to GET a list of clients (end-users) under your partner account based on a search pattern.
Prerequisites
To use the Partner API you must meet the following criteria
- Have a working development environment.
- Have an active Partner account. If you need a partner account you can sign up here.
- Enabled your account to use the API and set the access controls.
- Have valid API Credentials.
- Optional - Setup your development environment to initially use the Sandbox Testing Portal.
For Partner API reference documentation please see https://portal.my-engine.com/apidocs/index.html
Example Code
The examples below use the sandbox for testing. For a production environment remember to change the following:
- API Url
- Partner ID
- Partner API Key
<?php
/**
* client-search.php
*
* This example with do an API GET for a list of existing clients under that partner that match a search criteria.
* We will only request certain fields as well.
*
*/
$apiPartnerId = "<PartnerID>";
$apiSecretKey = "___PartnerKey___";
$apiUrl = "https://sandbox.my-engine.com/api-v1/clients";
$crlf = "<br />";
// Set the parameters
$queryParameters = array();
//$queryParameters["search"] = "('username LIKE':'fred%')";
//$queryParameters["search"] = "('external_userid':'123456')";
//$queryParameters["search"] = "('id':'9987600')";
//$queryParameters["search"] = "('id >':'9987600')";
$queryParameters["search"] = "('id >':'9987600','id <':'9987610')";
$queryParameters["fields"] = "!(id,username,email,surname,active,client_status_id)";
// Init Curl
$curl = curl_init();
// API Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "$apiPartnerId:$apiSecretKey");
// Set Curl Options
$parameters = http_build_query($queryParameters, '', '&');
curl_setopt($curl, CURLOPT_URL, $apiUrl . "?" . $parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// API GET
$jsonResult = curl_exec($curl);
// Check for a valid HTTP 200 success and process the returned result
// or handler the failure.
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) == 200) {
$result = json_decode($jsonResult, true);
if (json_last_error() == JSON_ERROR_NONE) {
// We have valid Json data, so lets display the results.
if ((is_array($result['data'])) && (!empty($result['data'])) ) {
foreach ($result['data'] as $client) {
echo "ClientID = " . $client["id"] . $crlf;
echo "Active Status = " . $client["active"] . $crlf;
echo "Client Verified Status = " . $client["client_status_id"] . $crlf;
echo "Username = " . $client["username"] . $crlf;
echo "Email = " . $client["email"] . $crlf;
echo "Surname = " . $client["surname"] . $crlf. $crlf;
}
} else {
echo "No data found." . $crlf;
}
}
} else {
echo "Response Code = " . curl_getinfo($curl, CURLINFO_RESPONSE_CODE) . $crlf;
$result = json_decode($jsonResult, true);
if (json_last_error() == JSON_ERROR_NONE) {
echo "error = " . $result["error"]["name"] . $crlf;
echo "url = " . $result["error"]["url"] . $crlf;
echo "message = " . $result["error"]["message"] . $crlf;
} else {
echo $jsonResult;
}
}
curl_close($curl);
/**
* client-search.cs
*
* This example with do an API GET for a list of existing clients under that partner that match a search criteria.
* We will only request certain fields as well.
*
*/
using Newtonsoft.Json;
using System;
using System.Collections.Specialized;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace clients_search
{
class Program
{
private const string apiPartnerId = "<PartnerID>";
private const string apiSecretKey = "_PartnerKey_";
private const string apiUrl = "https://sandbox.my-engine.com/api-v1/clients";
static async Task Main(string[] args)
{
// Build our parameters
NameValueCollection queryParameters = System.Web.HttpUtility.ParseQueryString(string.Empty);
//queryParameters.Add("search", "('username LIKE':'fred%')");
//queryParameters.Add("search", "('external_userid':'123456')");
//queryParameters.Add("search", "('id':'9987600')");
//queryParameters.Add("search", "('id >':'9987600')");
queryParameters.Add("search", "('id >':'9887600','id <':'9987610')");
queryParameters.Add("fields", "!(id,username,email,surname,active,client_status_id)");
// Create HTTP resource
HttpClient client = new HttpClient();
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Add("ContentType", "application/json");
// Set the Authorisation
var authToken = System.Text.Encoding.UTF8.GetBytes(apiPartnerId + ":" + apiSecretKey);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(authToken));
// Do the GET request.
HttpResponseMessage response = await client.GetAsync(apiUrl + "?" + queryParameters.ToString());
if (response.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync();
dynamic details = JsonConvert.DeserializeObject(content.Result);
if (details.ContainsKey("data"))
{
foreach (var item in details["data"])
{
// Display the data we want.
Console.WriteLine("ClientID = {0}", item["id"]);
Console.WriteLine("Active Status = {0}", item["active"]);
Console.WriteLine("Client Verified Status = {0}", item["client_status_id"]);
Console.WriteLine("Username = {0}", item["username"]);
Console.WriteLine("Email = {0}", item["email"]);
Console.WriteLine("Surname = {0} \n", item["surname"]);
}
}
else
{
Console.WriteLine("response = {0}", response);
Console.WriteLine("json response = {0}", details);
}
}
else
{
// Get the Json Error response and convert it
var jsonResponseStr = response.Content.ReadAsStringAsync().Result;
dynamic jsonResponse = JsonConvert.DeserializeObject(jsonResponseStr);
Console.WriteLine("name = {0}", jsonResponse["error"]["name"]);
Console.WriteLine("url = {0}", jsonResponse["error"]["url"]);
Console.WriteLine("message = {0}", jsonResponse["error"]["message"]);
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
//Dispose once all HttpClient calls are complete.
client.Dispose();
}
}
}
'
' client-search.vb
'
'
' This example with do an API GET for a list of existing clients under that partner that match a search criteria.
' We will only request certain fields as well.
'
'
Imports Newtonsoft.Json
Imports System
Imports System.Collections.Specialized
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Threading.Tasks
Module Program
Private Const apiPartnerId As String = "<PartnerID>"
Private Const apiSecretKey As String = "_PartnerKey_"
Private Const apiUrl As String = "https://sandbox.my-engine.com/api-v1/clients"
Public Sub Main(args As String())
clientsSearch().Wait()
End Sub
Public Async Function clientsSearch() As Task
' Build our parameters
Dim queryParameters As NameValueCollection = System.Web.HttpUtility.ParseQueryString(String.Empty)
'queryParameters.Add("search", "('username LIKE':'fred%')")
'queryParameters.Add("search", "('external_userid':'123456')")
'queryParameters.Add("search", "('id':'9987600')")
'queryParameters.Add("search", "('id >':'9987600')")
queryParameters.Add("search", "('id >':'9987600','id <':'9987610')")
queryParameters.Add("fields", "!(id,username,email,surname,active,client_status_id)")
' Create HTTP resource
Dim client As New HttpClient()
' Add an Accept header for JSON format.
client.DefaultRequestHeaders.Add("ContentType", "application/json")
' Set the Authorisation
Dim authToken = System.Text.Encoding.UTF8.GetBytes(apiPartnerId + ":" + apiSecretKey)
client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(authToken))
' Do the GET request.
Dim response As HttpResponseMessage = Await client.GetAsync(apiUrl + "?" + queryParameters.ToString())
If response.IsSuccessStatusCode Then
Dim content = response.Content.ReadAsStringAsync()
Dim details As Object = JsonConvert.DeserializeObject(content.Result)
If details.ContainsKey("data") Then
For Each item In details("data")
' View the entire record
' Console.WriteLine("data = {0}", item)
' Display the data we want.
Console.WriteLine("ClientID = {0}", item("id"))
Console.WriteLine("Active Status = {0}", item("active"))
Console.WriteLine("Client Verified Status = {0}", item("client_status_id"))
Console.WriteLine("Username = {0}", item("username"))
Console.WriteLine("Email = {0}", item("email"))
Console.WriteLine("Surname = {0} {1}", item("surname"), vbCrLf)
Next
Else
Console.WriteLine("response = {0}", response)
Console.WriteLine("json response = {0}", details)
End If
Else
' Get the Json Error response And convert it
Dim jsonResponseStr = response.Content.ReadAsStringAsync().Result
Dim jsonResponse As Object = JsonConvert.DeserializeObject(jsonResponseStr)
Console.WriteLine("name = {0}", jsonResponse("error")("name"))
Console.WriteLine("url = {0}", jsonResponse("error")("url"))
Console.WriteLine("message = {0}", jsonResponse("error")("message"))
Console.WriteLine("{0} ({1})", response.StatusCode, response.ReasonPhrase)
End If
'Dispose once all HttpClient calls are complete.
client.Dispose()
End Function
End Module
/**
* client-search.js
*
* This example with do an API GET for a list of existing clients under that partner that match a search criteria.
* We will only request certain fields as well.
*
*/
var apiPartnerId = "<PartnerID>";
var apiSecretKey = "_PartnerKey_";
var apiUrl = "https://sandbox.my-engine.com/api-v1/clients";
// Set the parameters
var queryParameters = {
"fields": "!(id,username,email,surname,active,client_status_id)",
// "search": "('username LIKE':'fred%')"
// "search": "('external_userid':'123456')"
// "search": "('id':'87600')"
// "search": "('id >':'87600')"
"search": "('id >':'87600','id <':'87610')"
};
var parameters = $.param(queryParameters, true);
// Setup the Ajax request
var settings = {
url: apiUrl + "?" + parameters,
headers: {
'Authorization': 'Basic ' + btoa(apiPartnerId + ":" + apiSecretKey),
'cache-control': 'no-cache'
},
crossDomain: true,
dataType: 'json',
async: true,
method: "GET"
};
// API GET
$.ajax(settings)
.done(function(response) {
$.each(response.data, function(index, value) {
console.log("ClientID = " + value.id);
console.log("Active Status = " + value.active);
console.log("Client Verified Status = " + value.client_status_id);
console.log("Username = " + value.username);
console.log("Email = " + value.email);
console.log("Surname = " + value.surname);
console.log(" ");
});
})
.fail(function(request, textStatus, errorThrown) {
try {
var errObj = $.parseJSON(request.responseText);
console.log("API Error - " + errObj.name);
console.log("API Msg - " + errObj.message);
console.log("API url - " + errObj.url);
} catch (e) {
console.log("Error - " + errorThrown);
console.log("Status - " + request.status);
console.log(request);
}
});