Soil Moisture

In this section we will test out the Soil Organic Carbon endpoints, which are:

  1. “/AFS/SoilMoisture” endpoint, allow the user to get the complete list of the land use that are in our calibrated system.
  2. “/AFS/SoilMoistureGeoJson” endpoint, which allow to request a soil moisture in geojson format.

SoilMoisture

Python

This endpoint allow you to get a tiff file format of the soil moisture.

In order to use it, you must define the following parameter:

  1. USEREMAIL
  2. APIKEY
  3. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  4. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  5. filterTime, Set the date filter can be onelastmonth, twolastmonth or none
  6. geojson_file_path (you can find it here county.geojson the county file of the example)

Load Libraries

import requests
import rasterio
import rasterio.plot
import folium
from rasterio.warp import calculate_default_transform, reproject, Resampling
from requests.auth import HTTPBasicAuth

Setting of the API

# Define the API parameters

fieldnumber="1"
action="none"
filterTime="onelastmonth"

# Define the url of the endpoint

api_endpoint = "https://www.api.automaticfarmsolutionwebapp.com/AFS/SoilMoistureNew?fieldnumber="

# Define the api url

api_url=api_endpoint+fieldnumber+"&action="+action+"&filterTime="+filterTime

# Set the useremail & Password

USEREMAIL="useremail"
APIKEY="apikey"

# Set the geojson file to send
geojson_file_path = "county.geojson"

Define python function

def convert_to_wgs84(input_raster_path, output_raster_path):
    # Open the input raster
    with rasterio.open(input_raster_path) as src:
        # Define the target CRS (WGS 84 - EPSG:4326)
        target_crs = 'EPSG:4326'

        # Get the affine transformation and dimensions of the new raster
        transform, width, height = calculate_default_transform(src.crs, target_crs, src.width, src.height, *src.bounds)

        # Create the options for reprojection
        kwargs = src.meta.copy()
        kwargs.update({
            'crs': target_crs,
            'transform': transform,
            'width': width,
            'height': height
        })

        # Reproject the raster to WGS 84
        with rasterio.open(output_raster_path, 'w', **kwargs) as dst:
            for i in range(1, src.count + 1):
                reproject(
                    source=rasterio.band(src, i),
                    destination=rasterio.band(dst, i),
                    src_transform=src.transform,
                    src_crs=src.crs,
                    dst_transform=transform,
                    dst_crs=target_crs,
                    resampling=Resampling.nearest
                )
def post_request_with_geojson(geojson_file_path, api_url):
    # Leggi il file GeoJSON
    with open(geojson_file_path, 'r') as file:
        geojson_data = file.read()

    # Specifica l'header per la POST request
    headers = {'Content-Type': 'application/json'}

    # Effettua la POST request
    response = requests.post(api_url, 
                             data=geojson_data, 
                             headers=headers,
                             auth=HTTPBasicAuth(USEREMAIL, APIKEY))
    
    if response.status_code == 200:
        # Save the response as a temporary raster file
        temp_raster_path = "temp_raster.tif"
        with open(temp_raster_path, 'wb') as temp_raster_file:
            temp_raster_file.write(response.content)

        # Convert the raster to WGS 84 (EPSG:4326)
        wgs84_raster_path = "temp_raster_wgs84.tif"
        convert_to_wgs84(temp_raster_path, wgs84_raster_path)

        # Open the WGS 84 raster using rasterio
        wgs84_raster = rasterio.open(wgs84_raster_path)

        # Read the image as a numpy array
        data = wgs84_raster.read(1)

        # Get the extent of the image
        xmin, ymin, xmax, ymax = wgs84_raster.bounds

        # Create a folium map centered at the center of the extent of the image
        center = [(ymin+ymax)/2, (xmin+xmax)/2]
        m = folium.Map(location=center, zoom_start=16)

        # Add the tif file as a raster layer
        overlay = folium.raster_layers.ImageOverlay(
            image=data,
            bounds=[[ymin, xmin], [ymax, xmax]],
            colormap=lambda x: (0, 0, 0, x/255),
            mercator_project=True)
        
        overlay.add_to(m)

        # Visualize the map
        return m
    else:
        print("Error during the request.")
        return None
# Make the POST request
m = post_request_with_geojson(geojson_file_path, api_url)

# Visualize the results

m

R

This endpoint allow you to get a tiff file format of the soil moisture.

In order to use it, you must define the following parameter:

  1. USEREMAIL
  2. APIKEY
  3. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  4. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  5. filterTime, Set the date filter can be onelastmonth, twolastmonth or none
  6. file_path_to_geojson (you can find it here county.geojson the county file of the example)
# import libraries

library(tictoc)
library(httr)
library(gt)
library(tidyverse)
library(raster)
library(mapview)

# Define the api parameters

fieldnumber="1"
action="none"
filterTime="onelastmonth"

# Define the url of the API

api_endpoint <- "https://www.api.automaticfarmsolutionwebapp.com/AFS/SoilMoistureNew?fieldnumber="

# Define the API call

api_url=paste0(api_endpoint, fieldnumber, "&action=",action, "&filterTime=", filterTime)

# Set the useremail & Password

USEREMAIL="useremail"
APIKEY="apikey"

# Path to the GeoJSON file

file_path_to_geojson = "county.geojson"

# Get the start time to API Call

tic()

# Make the POST request

r <- POST(
  api_url,
  httr::authenticate(
    user = Sys.getenv(USEREMAIL),
    password = Sys.getenv(APIKEY)
  ),
  body=httr::upload_file(file_path_to_geojson)
)

# Print out the seconds needed to get the satellite image

print("The API needed:")
toc()

# Get the status of the request

httr::status_code(r)

# Visulize the vegetation index

bin_raster<-readBin(r$content, what = "raw", n=length(r$content))

writeBin(bin_raster, con = "raster.tif")

raster <- raster::raster("raster.tif")

mapview(raster)

Node.js

This endpoint allow you to get a tiff file format of the soil moisture.

In order to use it, you must define the following parameter:

  1. USEREMAIL
  2. APIKEY
  3. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  4. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  5. filterTime, Set the date filter can be onelastmonth, twolastmonth or none
  6. geojsonFilePath (you can find it here county.geojson the county file of the example)
  7. rasterFilePath, is the path to save the raster file.
// load libraries

const axios = require('axios');
const fs = require('fs');

// Set the username & API key
const username = 'XXXXXXXXXXXXXXXXX';
const password = 'XXXXXXXXXXXXXXXXXXX';

// Set the api parameters

const fieldnumber="1";
const action="none";
const filterTime='onelastmonth';

// Set api url
const api_url = 'https://www.api.automaticfarmsolutionwebapp.com/AFS/SoilMoistureNew?fieldnumber=';

// Set api endpoint
const apiendpoint = api_url.concat(fieldnumber, "&action=",action,"&filterTime=",filterTime);

// Set the path to the local GeoJson that you want to use

const geojsonFilePath = './county.geojson';

// Set the path to save the raster that we will recive
const rasterFilePath = './file.tif';

async function makePostRequest() {

  const geojsonFile = fs.readFileSync(geojsonFilePath, 'utf8');

  const authHeader = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');

  try {
    const response = await axios.post(apiendpoint, geojsonFile, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': authHeader,
      },
      responseType: 'arraybuffer',
    });
    
    fs.writeFileSync(rasterFilePath, response.data);

    console.log('The raster file was locally saved', rasterFilePath);
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

makePostRequest();

Java

Work in progress

SoilMoistureGeoJson

Python

This endpoint allow you to get a geojson file format of the soil moisture.

In order to use it, you must define the following parameter:

  1. USEREMAIL
  2. APIKEY
  3. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  4. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  5. filterTime, Set the date filter can be onelastmonth, twolastmonth or none
  6. geojsonFilePath (you can find it here county.geojson the county file of the example)
# Load the libraries

import requests
import fiona
import geopandas as gpd
from requests.auth import HTTPBasicAuth

# Define the API parameters

fieldnumber="1"
action="none"
filterTime="onelastmonth"

# Define the url of the endpoint

api_endpoint = "https://www.api.automaticfarmsolutionwebapp.com/AFS/SoilMoistureGeoJsonNew?fieldnumber="

# Define the api url

api_url=api_endpoint+fieldnumber+"&action="+action+"&filterTime="+filterTime

# Set the useremail & Password

USEREMAIL="useremail"
APIKEY="apikey""

# Path to the GeoJSON file

file_path_to_geojson = "county.geojson"

# Read the GeoJSON file contents

with open(file_path_to_geojson, "r") as file:
    geojson_data = file.read()

# Set the headers for the request

headers = {
    "Content-Type": "application/json"
}

# Make the POST request with the GeoJSON datas the request body

response = requests.post(api_url, 
                         data=geojson_data, 
                         headers=headers,
                         auth=HTTPBasicAuth(USEREMAIL, APIKEY))

b = bytes(response.content)

with fiona.BytesCollection(b) as f:
    crs = f.crs
    gdf = gpd.GeoDataFrame.from_features(f, crs=crs)

#  Visualize the data

gdf.explore("Data_2023.07.19")

R

This endpoint allow you to get a geojson file format of the soil moisture.

In order to use it, you must define the following parameter:

  1. USEREMAIL
  2. APIKEY
  3. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  4. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  5. filterTime, Set the date filter can be onelastmonth, twolastmonth or none
  6. file_path_to_geojson (you can find it here county.geojson the county file of the example)
# Load the libraries

library(tictoc)
library(httr)
library(geojsonio)
library(mapview)

# Define the api parameters

fieldnumber="1"
action="none"
filterTime="onelastmonth"

# Define the url of the API

api_endpoint <- "https://www.api.automaticfarmsolutionwebapp.com/AFS/SoilMoistureGeoJsonNew?fieldnumber="

# Define the API call

url=paste0(api_endpoint, fieldnumber, "&action=",action, "&filterTime=", filterTime)

# Set the useremail & Password

USEREMAIL="useremail"
APIKEY="apikey"

# Path to the GeoJSON file

file_path_to_geojson = "county.geojson"

# Get the start time to API Call

tic()

# Make the POST request

api_call <- POST(
  url,
  httr::authenticate(
    user = Sys.getenv(USEREMAIL),
    password = Sys.getenv(APIKEY)
  ),
  body=httr::upload_file(file_path_to_geojson)
)

# Print out the seconds needed to create the prescription map

print("The API needed:")
toc()

# Visualize the prescription map

vegetation_index <- content(api_call, as = "text", type = "application/geo+json")

Node.js

This endpoint allow you to get a geojson file format of the soil moisture.

In order to use it, you must define the following parameter:

  1. USEREMAIL
  2. APIKEY
  3. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  4. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  5. filterTime, Set the date filter can be onelastmonth, twolastmonth or none
  6. file_path_to_geojson (you can find it here county.geojson the county file of the example)
// Load Libraries

const fs = require('fs');
const axios = require('axios');

// Set the useremail & passowrd

const useremail = 'XXXXXXXXXXXXX';
const apikey = 'XXXXXXXXXXXXX';

// Set the api parameters

const fieldnumber="1";
const action="none";
const filterTime='onelastmonth';

// Set api url
const api_url = 'https://www.api.automaticfarmsolutionwebapp.com/AFS/SoilMoistureGeoJsonNew?fieldnumber=';

// Set api endpoint
const apiEndpoint = api_url.concat(fieldnumber, "&action=",action,"&filterTime=",filterTime);

// Set path to load the geojson to send as body of POST request to the API

const file_path_to_geojson = './county.geojson';

// Set path to save the geojson prescription map

const outputFilePath = './result.geojson'; 

(async () => {
  try {

    const geojsonContent = await fs.promises.readFile(file_path_to_geojson, 'utf8');
    
    const geojsonObject = JSON.parse(geojsonContent);

    
    const authHeader = `Basic ${Buffer.from(`${useremail}:${apikey}`).toString('base64')}`;

    
    const response = await axios.post(apiEndpoint, geojsonObject, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': authHeader
      }
    });

    const resultGeoJSON = response.data;
    
    console.log('Answer From the API:', resultGeoJSON);

    await fs.promises.writeFile(outputFilePath, JSON.stringify(resultGeoJSON, null, 2), 'utf8');

  } catch (err) {
    console.error('Error:', err.message);
  }
})();

Java

Work in progress

SoilMoistureTemporalVariationJson

Python

In this example we will test the SoilMoistureTemporalVariationJson which allow the user to get a json with the temporal variation of the vegetation index.

To use the following example you have to replace:

  1. USEREMAIL
  2. APIKEY
  3. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  4. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  5. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  6. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  7. file_path_to_geojson (you can find it here county.geojson the county file of the example)

With your information and let’s try out the API.

# Load the libraries

import requests
import json
import pandas as pd
from requests.auth import HTTPBasicAuth

# Define the API parameters

fieldnumber="1"
action="none"
filterTime="onelastmonth"

# Define the url of the endpoint

api_endpoint = "https://www.api.automaticfarmsolutionwebapp.com/AFS/SoilMoistureTemporalVariationJsonNew?fieldnumber="

# Define the api url

api_url=api_endpoint+fieldnumber+"&action="+action

# Set the useremail & Password

USEREMAIL="XXXXXXX"
APIKEY="XXXXXXX"

# Path to the GeoJSON file

file_path_to_geojson = "county.geojson"

# Read the GeoJSON file contents

with open(file_path_to_geojson, "r") as file:
    geojson_data = file.read()

# Set the headers for the request

headers = {
    "Content-Type": "application/json"
}

# Make the POST request with the GeoJSON data as the request body

response = requests.post(api_url, 
                         data=geojson_data, 
                         headers=headers,
                         auth=HTTPBasicAuth(USEREMAIL, APIKEY))

response_bytes=response.content

response_str = response_bytes.decode('utf-8')

# Parse the JSON string
data = json.loads(response_str)

# Create a DataFrame
df = pd.DataFrame(data)

df.head()

R

In this example we will test the VegetationIndexTemporalVariationJson which allow the user to get a json with the temporal variation of the vegetation index.

To use the following example you have to replace:

  1. USEREMAIL
  2. APIKEY
  3. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  4. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  5. file_path_to_geojson (you can find it here county.geojson the county file of the example)

With your information and let’s try out the API.

# Load the libraries

library(tictoc)
library(httr)
library(geojsonio)
library(mapview)

# Define the api parameters

fieldnumber="1"
action="none"
filterTime="onelastmonth"

# Define the url of the API

api_endpoint <- "https://www.api.automaticfarmsolutionwebapp.com/AFS/SoilMoistureTemporalVariationJsonNew?fieldnumber="

# Define the API call

url=paste0(api_endpoint, fieldnumber, "&action=",action)

# Set the useremail & Password

USEREMAIL="useremail"
APIKEY="apikey"

# Path to the GeoJSON file

file_path_to_geojson = "county.geojson"

# Get the start time to API Call

tic()

# Make the POST request

api_call <- POST(
  url,
  httr::authenticate(
    user = Sys.getenv(USEREMAIL),
    password = Sys.getenv(APIKEY)
  ),
  body=httr::upload_file(file_path_to_geojson)
)

# Print out the seconds needed to create the prescription map

print("The API needed:")
toc()

# Visualize the prescription map
cont <- httr::content(api_call, as = "text", type = "application/json", encoding="UTF-8")
cont<-jsonlite::fromJSON(cont) %>% as.data.frame
cont

Node.js

In this example we will test the SoilMoistureTemporalVariationJson which allow the user to get a json with the temporal variation of the vegetation index.

To use the following example you have to replace:

  1. USEREMAIL
  2. APIKEY
  3. fieldnumber, The field number. You have to refereed to the field that you can get from the gid column of the UserField endpoint response
  4. action, the action must be setted as none, new, edit. If you want to receive the data based on the polygons saved in the past set none. If you want to add a new field set as new. If you want to change the shape of the polygons set edit.
  5. file_path_to_geojson (you can find it here county.geojson the county file of the example)

With your information and let’s try out the API.

// Load Libraries

const fs = require('fs');
const axios = require('axios');

// set the username and apikey
const useremail = 'XXXXXXXXXXXX';
const apikey = 'XXXXXXXXXXXX';

// Set the api parameters

const fieldnumber="1";
const action="none";

// Set api url
const api_url = 'https://www.api.automaticfarmsolutionwebapp.com/AFS/SoilMoistureTemporalVariationJsonNew?fieldnumber=';

// Set api endpoint
const apiUrl = api_url.concat(fieldnumber, "&action=",action);

const file_path_to_geojson = './county.geojson';

async function main() {
  try {
    const geojson = JSON.parse(fs.readFileSync(file_path_to_geojson, 'utf8'));
    const authHeader = `Basic ${Buffer.from(`${useremail}:${apikey}`).toString('base64')}`;

    const response = await axios.post(apiUrl, geojson, {
      headers: {
        Authorization: authHeader,
        'Content-Type': 'application/json',
      },
    });

    // Print the formatted JSON response to the console
    console.log(JSON.stringify(response.data, null, 2));
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

main();

Java

Work in progress

Easy - Fast - Customizable

Back to top