Code Examples of how to connect to the AHDB RB209 Web API Application

Details

There are three different types of connections within the API, each are documented here in different programming languages.

The first three examples are coded in C#: Those which have no parameters passed to them (Example 1), those which have parameters passed to them within the uri (Example 2), and those which have parameters passed to them within the body (Example 3).

The next three examples of connections are coded in AJAX: Those which have no parameters passed to them (Example 4), those which have parameters passed to them within the uri (Example 5), and those which have parameters passed to them within the body (Example 6).

If you have been supplied with a User Name and Licence Key, you can connect to the connections within the API.

If not and you would like to connect to the API, then you can request a licence key from here.

Your User Name and Licence Key or "Authentication Details" (Example 1: Lines 2 & 3), should be added to the connecting client (Example 1: Line 8, Example 4: Lines 15 - 17).

The examples provided here, connect to the CropGroup_List connection (Example 1: Line 11), CropType_List/{CropGroupID} connection (Example 2: Line 14), Recommendations connection (Example 3: Line 14), CropType_List connection (Example 4: Line 11), CropGrop_Item/{CropGroupID} connection (Example 5: Line 11), and SimplifiedPostTest connection (Example 6: Line 11) of the current version of the API (Example 1: Line 4).

When parameters are passed in the uri (Example 2: Line 14), they are appended on to the end of the url - if there is more than 1 parameter, then they must be appended in the correct order. However when parameters are passed in the body (Example 3: Lines 7 & 15), the parameters first need to be serialized into a Json format, and then added to the connecting client.

The connections return data in a Json format which when the data is more than just a single string, must be deserialized (Example 1: Line 16) before it can be used in code. In the case of Examples 1 and 2, these are Lists of type 'cropgroup' for Example 1, and type 'croptype' for Example 2. Example 3 returns a data structure of type 'dataoutput'. While Example 5 returns data as a string.

Please note that if you wish to connect to the Web API through AJAX, you will need to provide us with the url of the site(s) that you will be calling the API from. Please email your details along with your User Name to: nutrient.management@ahdb.org.uk, with the subject line 'Web API - AJAX connection details' and we will update our system as soon as possible.

Example 1 C# (no parameters)

//API Connection Details
string UserName = "...";        //Your User Name
string LicenceKey = "...";      //Your Licence Key
string ApiConnection = "https://rb209-api-v1.ahdb.org.uk";

//Add Authentication details
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", UserName, LicenceKey))));

//Connect to API & retrieve data
var url = string.Format("{0}/api/arable/cropgroup_list", ApiConnection);
var task = client.GetAsync(url);
var ReturnedData = task.Result.Content.ReadAsStringAsync().Result;

//Deserialize output details
List<cropgroup> CropGroupList = JsonConvert.DeserializeObject<List<cropgroup>>(ReturnedData);

Example 2 C# (parameters within uri)

//API Connection Details
string UserName = "...";        //Your User Name
string LicenceKey = "...";      //Your Licence Key
string ApiConnection = "https://rb209-api-v1.ahdb.org.uk";

//Collect input parameter
int CropGroupID = int.Parse(ddlCropGroup.SelectedItem.Value);

//Add Authentication details
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", UserName, LicenceKey))));

//Connect to API & retrieve data
var url = string.Format("{0}/api/arable/croptype_list/{1}", ApiConnection, CropGroupID);
var task = client.GetAsync(url);
var ReturnedData = task.Result.Content.ReadAsStringAsync().Result;
  
//Deserialize output details
List<cropgroup> CropGroupList = JsonConvert.DeserializeObject<List<cropgroup>>(ReturnedData);

Example 3 C# (parameters within body)

//API Connection Details
string UserName = "...";        //Your User Name
string LicenceKey = "...";      //Your Licence Key
string ApiConnection = "https://rb209-api-v1.ahdb.org.uk";

//Serialize input details
var content = new StringContent(JsonConvert.SerializeObject(DataInput), Encoding.UTF8, "application/json");

//Add Authentication details
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", UserName, LicenceKey))));

//Connect to API & retrieve data
var url = string.Format("{0}/api/main/recommendations/", ApiConnection);
var task = client.PostAsync(url, content);
var ReturnedData = task.Result.Content.ReadAsStringAsync().Result;

//Deserialize output details
dataoutput DataOutput = JsonConvert.DeserializeObject<dataoutput>(ReturnedData);

Example 4 AJAX (no parameters)

//API Connection Details
var UserName = "...";        //Your User Name
var LicenceKey = "...";      //Your Licence Key
var ApiConnection = "https://rb209-api-v1.ahdb.org.uk";

//Clear dropdown list
$('#ddlCropType').empty();

$.ajax({
    type: "GET",
    url: ApiConnection + "/api/arable/croptype_list/",
    dataType: "json",
    data: {},
    //Pass in Authorization details
    beforeSend: function (xhr){
        xhr.setRequestHeader('Authorization', "Basic " + btoa(UserName + ":" + LicenceKey))
    },
    success: function (CropTypeItems) {
        //Process output data: populate Crop Type dropdown list
        $.each(CropTypeItems, function (i, CropType) {
            $('#ddlCropType').append('<option value="' + CropType.CropTypeID + '">' + CropType.CropTypeName + '</option>');
        });
    },
    error: function () {
        alert('Failed to connect to API connection: CropType_List');
    }
});

Example 5 AJAX (parameters within uri)

//API Connection Details
var UserName = "...";        //Your User Name
var LicenceKey = "...";      //Your Licence Key
var ApiConnection = "https://rb209-api-v1.ahdb.org.uk";

//Collect input parameter
var CropGroupID = $("#txtCropGroupID").val();

$.ajax({
    type: "GET",
    url: ApiConnection + "/api/arable/cropgroup_item/" + CropGroupID,
    dataType: "json",
    data: {},
    //Pass in Authorization details
    beforeSend: function (xhr){
        xhr.setRequestHeader('Authorization', "Basic " + btoa(UserName + ":" + LicenceKey))
    },
    success: function(data){
        //Output is a string
        $('#lblCropGroup_Text').text(data.CropGroupName);
    },
    error: function () {
        alert('Failed to connect to API connection: CropGroup_Item');
    }
});

Example 6 AJAX (parameters within body)

//API Connection Details
var UserName = "...";        //Your User Name
var LicenceKey = "...";      //Your Licence Key
var ApiConnection = "https://rb209-api-v1.ahdb.org.uk";

//Collect input parameters
var DataInput = { "inId": $("#txtInID").val(), "inName": $("#txtInName").val() };

$.ajax({
    type: "POST",
    url: ApiConnection + "/api/main/simplifiedposttest/",
    dataType: "json",
    data: DataInput,
    //Pass in Authorization details
    beforeSend: function (xhr){
        xhr.setRequestHeader('Authorization', "Basic " + btoa(UserName + ":" + LicenceKey))
    },
    success: function(ReturnedData){
        //Process output data
        $('#lblID').text(ReturnedData.outId);
        $('#lblName').text(ReturnedData.outName);
    },
    error: function () {
            alert('Failed to connect to API connection: SimplifiedPostTest');
    }
});