Problem
How do I regrade (upgrade/downgrade) a live service using the Partner API?
Using the Partner RESTful API how to I upgrade or downgrade (regrade) a product (live service)?
Solution
The following example of code shows you how to regarde a live service
Note, in order to regrade a product you must first know the liveservice id. This can be optained by looking up the product and getting the liveservice id from the field name live_service_id.
Once you have the liveservice id its always a good idea to do a GET on the /live_services/{id} and look at the fieldname regarde_servicenames. This will give you all the possible packages its possible to regrade to.
It is good practice to ensure you have enough partner credits before regarding. Current Partner Credit balance and the cost in credits for a service can be found using the end point /live_services/service_names. However if you do have insufficient Partner Credits during the regrade operation you will get a 405 error.
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 Poral.
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
/**
* liveservices-regrade.php
*
* This example will regrade a live service. A live service is any of the
* products made available in the portal (outMail, Profilter, fakeMX,
* backupMX, masterDNS and backupDNS).
*
* You need to know the LiveService ID for the desired service you wish to
* regrade.
*
* For example, assuming you are trying to upgrade an outMail service
* You can do a GET from /outmails, looking for the field name live_service_id.
*
* To regrade a service we use the /live_services/id end point in the API
*
* To get a list of package names that you can regrade this product to see the
* field name regrade_servicenames by doing a GET of the liveservice/id
*
*/
$apiPartnerId = "<PartnerID>";
$apiSecretKey = "___PartnerKey___";
$apiUrl = "https://sandbox.my-engine.com/api-v1/live_services";
$crlf = "<br />";
// Set the ID of the service to regrade.
// Remember this is the live_service ID (live_service_id)
// If you're not sure then do a GET first and use the field live_service_id
$id = "1234931";
// Create the array for the liveservice data
$liveService = array();
$liveService["tariff_service_name"] = "Outmail1000";
// Init Curl
$curl = curl_init();
// API Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "$apiPartnerId:$apiSecretKey");
// Set Curl Options
curl_setopt($curl, CURLOPT_URL, $apiUrl . '/' . $id);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// API PATCH
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($liveService));
// Tell it we're sending a JSON set of data in the POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
// API PATCH
$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) {
echo "status = " . $result["meta"]["success"] . $crlf;
} else {
print_r($result);
}
} 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);
/**
* liveservices-regrade.cs
*
* This example will regrade a live service. A live service is any of the
* products made available in the portal (outMail, Profilter, fakeMX,
* backupMX, masterDNS and backupDNS).
*
* You need to know the LiveService ID for the desired service you wish to
* regrade.
*
* For example, assuming you are trying to upgrade an outMail service
* You can do a GET from /outmails, looking for the field name live_service_id.
*
* To regrade a service we use the /live_services/id end point in the API
*
* To get a list of package names that you can regrade this product to see the
* field name regrade_servicenames by doing a GET of the liveservice/id
*
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace liveservices_regrade
{
class Program
{
private const string apiPartnerId = "<PartnerID>";
private const string apiSecretKey = "_PartnerKey_";
private const string apiUrl = "https://sandbox.my-engine.com/api-v1/live_services";
static void Main(string[] args)
{
// Set the ID of the service to regrade.
// Remember this is the live_service ID (live_service_id)
// If you're not sure then do a GET first and use the field live_service_id
string id = "1234931";
// Create the patch client data
Dictionary<string, string> liveService = new Dictionary<string, string>();
liveService.Add("tariff_service_name", "Outmail1000");
// Convert the Dictionary to Json
string liveServiceJsonStr = JsonConvert.SerializeObject(liveService, Formatting.Indented);
// 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));
// Create the content
var content = new StringContent(liveServiceJsonStr, Encoding.UTF8, "application/json");
// Do the PATCH
var response = client.PatchAsync(apiUrl + "/" + id, content).Result;
// Check the result for a valid HTTP 200 success and process the returned result
// or handler the failure.
if (response.IsSuccessStatusCode)
{
// Get the created ID
var jsonResponseStr = response.Content.ReadAsStringAsync().Result;
dynamic jsonResponse = JsonConvert.DeserializeObject(jsonResponseStr);
if (jsonResponse.ContainsKey("data"))
{
Console.WriteLine("status = {0}", jsonResponse["meta"]["success"]);
}
else
{
Console.WriteLine("response = {0}", response);
Console.WriteLine("json response = {0}", jsonResponse);
}
}
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();
}
}
}
'
' liveservices-regrade.vb
'
' This example will regrade a live service. A live service Is any of the
' products made available in the portal (outMail, Profilter, fakeMX,
' backupMX, masterDNS And backupDNS).
'
' You need to know the LiveService ID for the desired service you wish to
' regrade.
'
' For example, assuming you are trying to upgrade an outMail service
' You can do a GET from /outmails, looking for the field name live_service_id.
'
' To regrade a service we use the /live_services/id end point in the API
'
' To get a list of package names that you can regrade this product to see the
' field name regrade_servicenames by doing a GET of the liveservice/id
'
'
Imports Newtonsoft.Json
Imports System
Imports System.Collections.Generic
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Text
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/live_services"
Sub Main(args As String())
' Set the ID of the service to regrade.
' Remember this Is the live_service ID (live_service_id)
' If you're not sure then do a GET first and use the field live_service_id
Dim id As String = "1234931"
' Create the patch client data
Dim liveService As Dictionary(Of String, String) = New Dictionary(Of String, String)
liveService.Add("tariff_service_name", "Outmail1000")
' Convert the Dictionary to Json
Dim liveServiceJsonStr As String = JsonConvert.SerializeObject(liveService, Formatting.Indented)
' 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))
' Create the content
Dim content = New StringContent(liveServiceJsonStr, Encoding.UTF8, "application/json")
' Do the PATCH
Dim response = client.PatchAsync(apiUrl + "/" + id, content).Result
' Check the result for a valid HTTP 200 success And process the returned result
' Or handler the failure.
If (response.IsSuccessStatusCode) Then
' Get the created ID
Dim jsonResponseStr = response.Content.ReadAsStringAsync().Result
Dim jsonResponse As Object = JsonConvert.DeserializeObject(jsonResponseStr)
If jsonResponse.ContainsKey("data") Then
Console.WriteLine("status = {0}", jsonResponse("meta")("success"))
Else
Console.WriteLine("response = {0}", response)
Console.WriteLine("json response = {0}", jsonResponse)
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 Sub
End Module
/**
* liveservices-regrade.js
*
* This example will regrade a live service. A live service is any of the
* products made available in the portal (outMail, Profilter, fakeMX,
* backupMX, masterDNS and backupDNS).
*
* You need to know the LiveService ID for the desired service you wish to
* regrade.
*
* For example, assuming you are trying to upgrade an outMail service
* You can do a GET from /outmails, looking for the field name live_service_id.
*
* To regrade a service we use the /live_services/id end point in the API
*
* To get a list of package names that you can regrade this product to see the
* field name regrade_servicenames by doing a GET of the liveservice/id
*
*/
var apiPartnerId = "<PartnerID>";
var apiSecretKey = "_PartnerKey_";
var apiUrl = "https://sandbox.my-engine.com/api-v1/live_services";
// Set the ID of the service to regrade.
// Remember this is the live_service ID (live_service_id)
// If you're not sure then do a GET first and use the field live_service_id
var id = "1234931";
var jsondata = { "tariff_service_name": "Outmail1000" };
// Setup the Ajax request
var settings = {
url: apiUrl + '/' + id,
headers: {
'Authorization': 'Basic ' + btoa(apiPartnerId + ":" + apiSecretKey),
'cache-control': 'no-cache'
},
crossDomain: true,
// Uncomment the lines below if you want to POST data as JSON.
// If so comment the "data: jsondata" out
// contentType: 'application/json',
// data: JSON.stringify(jsondata),
// Comment the line below out, if you've uncomment the two line above.
// The "data: jsondata" method will POST data as application/x-www-form-urlencoded
data: jsondata,
dataType: 'json',
async: true,
method: "PATCH"
};
// API PATCH
$.ajax(settings)
.done(function(response) {
console.log("status = " + response.meta.success);
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);
}
});