import requests
import rasterio
import rasterio.plot
import folium
from rasterio.warp import calculate_default_transform, reproject, Resampling
from requests.auth import HTTPBasicAuthDEM
In this part we will focus on two endpoint:
- “AFS/DEMtiff” endpoint, which allow the user to get the digital elevation model for the Area of Interest in tiff format
- “/AFS/DEMgeojson” endpoint, which allow the user to get the digital elevation model for the Area of Interest in geojson format
DEMtiff
Python
In this example we will test the DEMtiff which allow the user to get the digital elevation model for the Area of Interest in tiff format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- 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
Setting of the API
# Define the url of the API
api_url = "https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMtiff?"
# 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
mR
In this example we will test the DEMtiff which allow the user to get the digital elevation model for the Area of Interest in tiff format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- 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.
# import libraries
library(tictoc)
library(httr)
library(gt)
library(tidyverse)
library(raster)
library(mapview)
# Define the url of the API
api_url <- "https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMtiff?"
# 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:")[1] "The API needed:"
toc()2.69 sec elapsed
# Get the status of the request
httr::status_code(r)[1] 200
# 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, layer.name="DEM (m)")Node.js
In this example we will test the DEMtiff which allow the user to get the digital elevation model for the Area of Interest in tiff format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- 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 axios = require('axios');
const fs = require('fs');
// Set the username & API key
const username = 'XXXXXXXXXXXXXXXXX';
const password = 'XXXXXXXXXXXXXXXXXXX';
// Set api endpoint
const apiendpoint = 'https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMtiff?';
// 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
In this example we will test the DEMtiff which allow the user to get the digital elevation model for the Area of Interest in tiff format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- 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.
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class VegetationIndex {
public static void main(String[] args) {
String apiUrl = "https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMtiff?";
String username = "XXXXXXXXXXXXXXXXXXXXXX";
String password = "XXXXXXXXXXXXXXXXXX";
String geojsonFilePath = "county.geojson";
String geojsonFile = "";
try {
geojsonFile = new String(Files.readAllBytes(Paths.get(geojsonFilePath)));
} catch (IOException e) {
e.printStackTrace();
}
// Imposta l'header per l'autenticazione base
String authHeader = "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
try {
// Effettua la richiesta POST all'API
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", authHeader);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(geojsonFile.getBytes());
os.flush();
// Gestisci la risposta
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Salva il file raster ottenuto in risposta
String rasterFilePath = "raster_file.tif"; // Sostituisci con il percorso in cui vuoi salvare il file raster
try (InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream(rasterFilePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
System.out.println("The raster file it was saved correctly: " + rasterFilePath);
} else {
System.out.println("An error occured: " + conn.getResponseMessage());
}
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}DEMgeojson
Python
In this example we will test the DEMgeojson which allow the user to get the digital elevation model for the Area of Interest in geojson format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- 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 fiona
import geopandas as gpd
from requests.auth import HTTPBasicAuth
# Define the url of the API
url = "https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMgeojson"
# Set the useremail & Password
USEREMAIL="email"
APIKEY="password"
# 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(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
In this example we will test the DEMgeojson which allow the user to get the digital elevation model for the Area of Interest in geojson format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- 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 url of the API
url = paste0("https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMgeojson?")
# 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:")[1] "The API needed:"
toc()1.28 sec elapsed
# Visualize the prescription map
vegetation_index <- content(api_call, as = "text", type = "application/geo+json")
vegetation_index<-geojson_sp(vegetation_index)
mapview(vegetation_index, zcol=names(vegetation_index)[1])Node.js
In this example we will test the DEMgeojson which allow the user to get the digital elevation model for the Area of Interest in geojson format
To use the following example you have to replace:
- USEREMAIL
- APIKEY
- 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 useremail & passowrd
const useremail = 'XXXXXXXXXXXXX';
const apikey = 'XXXXXXXXXXXXX';
// Set API Url
const apiEndpoint='https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMgeojson';
// 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
Easy - Fast - Customizable











