An example project using PHP and JS to create a dynamic wheel selector.
To run this example project:
php/tyre-wheel-selector.php.<?php
/**
* Class VehicleLogicAPI
*
* Wrapper for the Vehicle Logic REST API.
*/
class VehicleLogicAPI
{
private string $username;
private string $password;
private string $token = '';
public function __construct(string $username, string $password)
{
// start a new session if one has not been started
if(session_status() !== PHP_SESSION_ACTIVE)
session_start();
$this->username = $username;
$this->password = $password;
// get an access token
$this->getToken();
}
/**
* Get an access token for the Vehicle Logic API
*/
private function getToken(): void
{
// only get a new token if one doesn't exist in the session, or the current one has expired
if(!isset($_SESSION['token_data']) || time() > $_SESSION['token_data']['expire_time'])
{
// get a new token
$data = $this->query(
'token',
[
'grant_type' => 'password',
'username' => $this->username,
'password' => $this->password
],
'POST',
[
'Content-Type: application/x-www-form-urlencoded'
]
);
// store the new token
$_SESSION['token_data'] = $data;
$this->token = $data['access_token'];
$token_expires = time() + $data['expires_in'];
$_SESSION['token_data']['expire_time'] = $token_expires;
}
else
{
// use the token stored in the session
$this->token = $_SESSION['token_data']['access_token'];
}
}
/**
* Perform a request to the Vehicle Logic API using cURL.
* The JSON response is decoded and returned as an array.
* Returns FALSE on fail.
*
* @param string $endpoint Endpoint path e.g. 'tyres/patterns'
* @param array $data Query parameters
* @param string $method Request method e.g. 'GET' or 'POST'
* @param array $headers Request headers
* @return array|bool
*/
public function query(
string $endpoint,
array $data = [],
string $method = 'GET',
array $headers = []
): array|false
{
// get new token if needed
if($endpoint !== 'token') $this->getToken();
$uri = 'https://api.vehiclelogic.com.au/'.$endpoint;
$query_string = '';
if(count($data) > 0)
{
$query_string = http_build_query($data);
// add parameters to the URI if this is a GET request
if(strtolower($method) === 'get')
{
$uri .= '?'.$query_string;
}
}
$ch = curl_init($uri);
// these options enforce SSL
// may have to change both to 0 for local testing
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
// add access token to headers if headers are not set
// the only endpoint using custom headers is /token, so this is not needed
if(empty($headers))
{
$headers = ['Authorization: Bearer '.$this->token];
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// set up POST options if this is a POST request
if(strtolower($method) === 'post')
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$encoded_result = curl_exec($ch);
// check if cURL request failed
if($encoded_result !== false)
{
$response_code = intval(curl_getinfo($ch, CURLINFO_RESPONSE_CODE));
if($response_code !== 200)
{
// fail because the response code was not 200 (OK)
return false;
}
// decode cURL response
$result = json_decode($encoded_result, true);
if(isset($result['Items']) && empty($result['Items']))
{
// fail because a paged result has no results
return false;
}
else
{
return $result;
}
}
else
{
return false;
}
}
}
$api = new VehicleLogicAPI('USERNAME', 'PASSWORD');
$tyre_brands = $api->query(
'tyres/brands',
[
'page' => 1,
'perpage' => 5
]);
echo 'First 5 tyre brands:'.PHP_EOL;
print_r($tyre_brands);
$michelin_tyre_patterns = $api->query(
'tyres/patterns',
[
'page' => 1,
'perpage' => 5,
'tyrebrandids[]' => 1
]);
echo 'First 5 Michelin tyre patterns:'.PHP_EOL;
print_r($michelin_tyre_patterns);
$vehicle_makes = $api->query(
'vehicles/makes',
[
'page' => 1,
'perpage' => 5
]);
echo 'First 5 vehicle makes:'.PHP_EOL;
print_r($vehicle_makes);
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace VehicleLogicApiSample
{
static class Program
{
private const string Username = "<your_username_here";
private const string Password = "<your_password_here>";
private const string TyresBrandsPath = "/tyres/brands";
private const string TyresPatternsPath = "/tyres/patterns";
private const string VehicleMakesPath = "/vehicles/makes";
static void Main(string[] args)
{
using (var api = new VehicleLogicApi(Username, Password))
{
// Shared request query parameters
var paginationParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Page", "1"),
new KeyValuePair<string, string>("PerPage", "5"),
};
// Start the requests. As AuthenticatedQuery is an async method, these requests occur asynchronously.
var tyreBrandsRequest = api.AuthenticatedQuery(TyresBrandsPath, paginationParams);
var michelinPatternsParams = paginationParams.Concat(
new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("TyreBrandIds[]", "1"),
}
);
var michelinPatternsRequest = api.AuthenticatedQuery(TyresPatternsPath, michelinPatternsParams);
var vehicleMakesRequest = api.AuthenticatedQuery(VehicleMakesPath, paginationParams);
// Wait for requests to finish and display results
using (var tyreBrandsResponse = tyreBrandsRequest.Result)
{
tyreBrandsResponse.EnsureSuccessStatusCode();
Console.WriteLine("First 5 tyre brands:");
Console.WriteLine(JsonConvert.DeserializeObject(tyreBrandsResponse.Content.ReadAsStringAsync().Result));
Console.WriteLine();
}
using (var tyrePatternsResponse = michelinPatternsRequest.Result)
{
tyrePatternsResponse.EnsureSuccessStatusCode();
Console.WriteLine("First 5 Michelin tyre patterns:");
Console.WriteLine(JsonConvert.DeserializeObject(tyrePatternsResponse.Content.ReadAsStringAsync().Result));
Console.WriteLine();
}
using (var vehicleMakesResponse = vehicleMakesRequest.Result)
{
vehicleMakesResponse.EnsureSuccessStatusCode();
Console.WriteLine("First 5 vehicle makes:");
Console.WriteLine(JsonConvert.DeserializeObject(vehicleMakesResponse.Content.ReadAsStringAsync().Result));
Console.WriteLine();
}
}
}
}
/// <summary>
/// Handles authentication and provides helper functions to make requests to the Vehicle Logic API.
/// </summary>
public class VehicleLogicApi : IDisposable
{
private const string ApiUrlBase = "https://api.vehiclelogic.com.au";
private const string TokenEndpointPath = "/token";
private readonly string _username;
private readonly string _password;
private readonly HttpClient _httpClient;
private AccessToken _token;
private Task<bool> _authenticationTask;
public VehicleLogicApi(string username, string password)
{
_username = username ?? throw new ArgumentException($"{nameof(username)} must be non null.");
_password = password ?? throw new ArgumentException($"{nameof(password)} must be non null.");
_httpClient = new HttpClient();
}
/// <summary>
/// Builds a request URL from the given path and query parameters then makes a request to the Vehicle Logic API
/// with the appropriate authentication headers and the given request body content (if any). Uses an existing
/// OAuth token if it exists and hasn't expired, otherwise it transparently requests a new token, or waits for
/// an existing authentication request to complete if there is already an authentication request in progress.
/// </summary>
/// <param name="urlPath">Endpoint path including leading /. e.g. '/tyres/patterns</param>
/// <param name="queryParameters">Parameters which will be added to the query segment of the request URL</param>
/// <param name="content">The content to be sent in the body of the request</param>
/// <returns>The HTTP response</returns>
public async Task<HttpResponseMessage> AuthenticatedQuery(
string urlPath,
IEnumerable<KeyValuePair<string, string>> queryParameters,
HttpContent content = null
)
{
if (urlPath == null) throw new ArgumentException($"{nameof(urlPath)} must be non null.");
// Make sure we are authorised with the API before continuing.
if (!await CheckAuthentication()) throw new Exception("Could not authenticate");
return await Query(
urlPath,
queryParameters,
content,
new AuthenticationHeaderValue("Bearer", _token.Token)
);
}
/// <summary>
/// Builds the query segment of a URL from a list of parameters
/// </summary>
/// <param name="parameters">The parameter name value pairs</param>
/// <returns>The escaped query string</returns>
public static string BuildQuery(IEnumerable<KeyValuePair<string, string>> parameters)
{
if (parameters == null) return "";
var encodedParams = parameters.Select(
kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"
);
return string.Join("&", encodedParams);
}
/// <summary>
/// First checks for an existing and returns true if one exists. Otherwise, starts a new authentication request
/// if there isn't already one in progress and returns whether or not the authentication request was successful.
/// </summary>
/// <returns>Whether the client is successfully authenticated</returns>
private async Task<bool> CheckAuthentication()
{
// return true if we already have a valid token.
if (_token != null && DateTime.UtcNow < _token.Expires) return true;
// Start an authentication task if there isn't already one
if (_authenticationTask == null) _authenticationTask = Authenticate();
// Return the result of the authentication request
var result = await _authenticationTask;
_authenticationTask = null;
return result;
}
/// <summary>
/// Create a new authentication request and return if it was successful
/// </summary>
/// <returns>Whether the authentication request was successful</returns>
private async Task<bool> Authenticate()
{
var content = new FormUrlEncodedContent(new Dictionary<string,string>
{
{"grant_type", "password"},
{"username", _username},
{"password", _password}
});
using (var response = await Query(TokenEndpointPath, null, content))
{
if (!response.IsSuccessStatusCode) return false;
var responseObject = JObject.Parse(await response.Content.ReadAsStringAsync());
var accessToken = (string) responseObject["access_token"];
var expires = DateTime.ParseExact(
(string) responseObject[".expires"],
CultureInfo.InvariantCulture.DateTimeFormat.RFC1123Pattern,
CultureInfo.InvariantCulture
);
_token = new AccessToken
{
Token = accessToken,
Expires = expires
};
return true;
}
}
private async Task<HttpResponseMessage> Query(
string urlPath,
IEnumerable<KeyValuePair<string, string>> parameters,
HttpContent content = null,
AuthenticationHeaderValue authHeader = null
)
{
if (urlPath == null) throw new ArgumentException($"{nameof(urlPath)} must be non null.");
var uri = $"{ApiUrlBase}{urlPath}?{BuildQuery(parameters)}";
using (var request = new HttpRequestMessage(HttpMethod.Get, new Uri(uri)))
{
request.Headers.Authorization = authHeader;
request.Content = content;
Console.WriteLine($"Starting HTTP request to {uri}");
return await _httpClient.SendAsync(request);
}
}
private class AccessToken
{
public string Token;
public DateTime Expires;
}
public void Dispose()
{
_httpClient.Dispose();
}
}
}