Skip to content

Latest commit

 

History

History
170 lines (112 loc) · 10.1 KB

File metadata and controls

170 lines (112 loc) · 10.1 KB

Create a Field Location

In lesson 2.1.1, you retrieved a list of fields associated with your account. In this lesson you will learn how to add a new field. This is a necessary step in order for you to retrieve weather data for any location.

First we will load some necessary packages.

suppressWarnings(suppressMessages(library(aWhereAPI)))
httr::set_config(httr::config( ssl_verifypeer = 0L ))

library(magrittr)
library(openxlsx)
Warning message:
: package ‘magrittr’ was built under R version 3.2.4Warning message:
: package ‘openxlsx’ was built under R version 3.2.4

Now, you will import some existing data with R that contains the necessary information about the new field to add. For reference, code for the call to retrieve your already-existing list of fields is provided.

data <- read.xlsx("example_trials.xlsx")
data$PlotSize <- data$PlotSize*1/4046.8564224 # convert to acres
head(data)
FarmerIdYearSeasonPlantingDateHarvestingDateLatitudeLongitudeAltitudePlotSubplotTreatRepNoTreatmentDescriptionNsourceNratePsourcePrateKsourceKratePlotSizeCropVarietyNetPlotHarvestAreaNoofRowsNoofPlantsStandCountNo.ofcobsTotalCobFreshWeightCobSubsampleFreshWeightStoverTotalFreshWeightStoverSubsampleFreshWeightStoverSubsampleDryWeightCoreSubsampleDryWeightGrainSubsampleOvenDryWeightCoreYieldStoverYieldGrainYield
1Farmer-12013Long rain41315414501.0982931.3921511791111ControlNone0None0None00.009340583MaizeKilima29.16612521111460560030057100NA0.50.9
2Farmer-12013Long rain41315414501.0982931.3921511792221UreaUrea60None0None00.009340583MaizeKilima29.16612522815.55107.960027057270NA0.61.2
3Farmer-12013Long rain41315414501.0982931.3921511793331TSP + UreaUrea60TSP20None00.009340583MaizeKilima29.166125236255101760027073310NA1.22.6
4Farmer-12013Long rain41315414501.0982931.3921511794441Minjingu powder + ureaUrea60Minjingu powder20None00.009340583MaizeKilima29.166125233246501060027092250NA1.21.5
5Farmer-12013Long rain41315414501.0982931.3921511795551Minjingu granular + ureaUrea60Minjingu granular20None00.009340583MaizeKilima29.16612524522.97202160017097250NA1.12
6Farmer-12013Long rain41315414501.0982931.3921511796661Minjingu mazao + ureaUrea60Minjingu mazao20None00.009340583MaizeKilima29.16612522929.97001560022087340NA1.31.9
api_key = "yizhexu@awhere.com"
api_secret = "********"

get_token(api_key, api_secret)
get_fields()
fieldNameAcresfarmIdfield_idLatitudeLongitude
1agra_uganda_vk0.0093agra_ugandaagra_uganda_11.233131.4979
2agra_uganda_vk0.0093406agra_ugandaagra_uganda_21.233131.498
3agra_uganda_vk0.0093406agra_ugandaagra_uganda_31.233131.498
4agra_uganda_vk0.009340583agra_ugandaagra_uganda_41.2331531.49786
5awhere_headquarter1awhere_farmer_1awhere_headquarter39.92524105.1066
6My First Field100Farm-100field139.8282-98.5795

The code below begins by updating the API endpoint to which we will send the request. It then constructs a data frame (similar to a table) with one row of data, and columns named "id", "name", "farmId", "acres", "latitude", and "longitude".

It is important to understand that JSON data is nested, meaning that it is constructed to contain different levels. Think of the structure like tree roots, with the trunk being the top level and the various roots branching off forming the nested sub-levels. Below, the code creating the data frame nests the latitude and longitude information under a top-level column named "centerPoint".

After the data frame (named postbody is created, we can easily convert it to JSON format using the R command "toJSON". You can view the API documentation showing how a properly-nested JSON request looks here.

api_endpoint <- "https://api.awhere.com/"
get_fields_url <- "v2/fields/"

i=5
postbody <- data.frame("id" = paste0("agra_uganda_", i), 
                  "name" = "agra_uganda_vk",
                  "farmId" = "agra_uganda", 
                  "acres" = data$PlotSize[[i]])
postbody$centerPoint <- data.frame("latitude" = data$Latitude[[i]], "longitude"= data$Longitude[[i]])

postbody <- toJSON(postbody, pretty=TRUE) %>% gsub("\\[|\\]", "", .)
postbody

'{ "id" : "agra_uganda_5" , "name" : "agra_uganda_vk" , "farmId" : "agra_uganda" , "acres" : 0.0093406 , "centerPoint" : { "latitude" : 1.0983 , "longitude" : 31.392

}

}'


The postbody is not the actual request, rather it is the information within the request that you want the API to "post" to its servers. To send the API request, use the httr command "POST", and include the correct endpoint, postbody, and your valid token.

While the POST request below may look more complicated than described, the additional code is primarily formatting the content of the request. Small variations, like failing to specify the content_type, can sometimes cause the request to fail.

request <- POST(paste0(api_endpoint, get_fields_url), 
                body = postbody, 
                content_type('application/json'),
                add_headers(Authorization = paste0("Bearer ",awhereEnv75247$token)))

content(request, as = "text")
No encoding supplied: defaulting to UTF-8.

'{"name":"agra_uganda_vk","acres":0.0093406,"centerPoint":{"latitude":1.0983,"longitude":31.392},"farmId":"agra_uganda","id":"agra_uganda_5","_links":{"self":{"href":"/v2/fields/agra_uganda_5"},"curies":[{"name":"awhere","href":"http://awhere.com/rels/{rel}","templated":true}],"awhere:observations":{"href":"/v2/weather/fields/agra_uganda_5/observations"},"awhere:forecasts":{"href":"/v2/weather/fields/agra_uganda_5/forecasts"},"awhere:plantings":{"href":"/v2/agronomics/fields/agra_uganda_5/plantings"},"awhere:agronomics":{"href":"/v2/agronomics/fields/agra_uganda_5/agronomicvalues"}}}'


The aWhereAPI package accomplishes the same function as the above codes, and significantly simplifies the problems of endpoints, nesting and formatting a POST request. Rather than require a specified endpoint, the command "CreateField" sends the call to the aWhere fields API by default. The command formats the JSON data and nests the latitude and longitude points for you rather than requiring advanced code, and sources your token from the R environment without being prompted.

i = 7
create_field(field_id = paste0("agra_uganda_", i), 
            latitude = data$Latitude[[i]], longitude= data$Longitude[[i]],
            farm_id = "agra_uganda", 
            field_name = "agra_uganda_vk", 
            acres = data$PlotSize[[i]])
No encoding supplied: defaulting to UTF-8.


Operation Complete