import requests
import rasterio
import rasterio.plot
import folium
from rasterio.warp import calculate_default_transform, reproject, Resampling
from requests.auth import HTTPBasicAuth
DEM
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
= "https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMtiff?"
api_url
# Set the useremail & Password
="useremail"
USEREMAIL="apikey"
APIKEY
# Set the geojson file to send
= "county.geojson" geojson_file_path
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)
= 'EPSG:4326'
target_crs
# Get the affine transformation and dimensions of the new raster
= calculate_default_transform(src.crs, target_crs, src.width, src.height, *src.bounds)
transform, width, height
# Create the options for reprojection
= src.meta.copy()
kwargs
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(=rasterio.band(src, i),
source=rasterio.band(dst, i),
destination=src.transform,
src_transform=src.crs,
src_crs=transform,
dst_transform=target_crs,
dst_crs=Resampling.nearest
resampling )
def post_request_with_geojson(geojson_file_path, api_url):
# Leggi il file GeoJSON
with open(geojson_file_path, 'r') as file:
= file.read()
geojson_data
# Specifica l'header per la POST request
= {'Content-Type': 'application/json'}
headers
# Effettua la POST request
= requests.post(api_url,
response =geojson_data,
data=headers,
headers=HTTPBasicAuth(USEREMAIL, APIKEY))
auth
if response.status_code == 200:
# Save the response as a temporary raster file
= "temp_raster.tif"
temp_raster_path with open(temp_raster_path, 'wb') as temp_raster_file:
temp_raster_file.write(response.content)
# Convert the raster to WGS 84 (EPSG:4326)
= "temp_raster_wgs84.tif"
wgs84_raster_path
convert_to_wgs84(temp_raster_path, wgs84_raster_path)
# Open the WGS 84 raster using rasterio
= rasterio.open(wgs84_raster_path)
wgs84_raster
# Read the image as a numpy array
= wgs84_raster.read(1)
data
# Get the extent of the image
= wgs84_raster.bounds
xmin, ymin, xmax, ymax
# Create a folium map centered at the center of the extent of the image
= [(ymin+ymax)/2, (xmin+xmax)/2]
center = folium.Map(location=center, zoom_start=16)
m
# Add the tif file as a raster layer
= folium.raster_layers.ImageOverlay(
overlay =data,
image=[[ymin, xmin], [ymax, xmax]],
bounds=lambda x: (0, 0, 0, x/255),
colormap=True)
mercator_project
overlay.add_to(m)
# Visualize the map
return m
else:
print("Error during the request.")
return None
# Make the POST request
= post_request_with_geojson(geojson_file_path, api_url)
m
# Visualize the results
m
R
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
<- "https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMtiff?"
api_url
# Set the useremail & Password
="useremail"
USEREMAIL="apikey"
APIKEY
# Path to the GeoJSON file
= "county.geojson"
file_path_to_geojson
# Get the start time to API Call
tic()
# Make the POST request
<- POST(
r
api_url,::authenticate(
httruser = 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
::status_code(r) httr
[1] 200
# Visulize the vegetation index
<-readBin(r$content, what = "raw", n=length(r$content))
bin_raster
writeBin(bin_raster, con = "raster.tif")
<- raster::raster("raster.tif")
raster
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',
;
})
.writeFileSync(rasterFilePath, response.data);
fs
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 {
= new String(Files.readAllBytes(Paths.get(geojsonFilePath)));
geojsonFile } catch (IOException e) {
.printStackTrace();
e}
// 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();
.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", authHeader);
conn.setDoOutput(true);
conn
OutputStream os = conn.getOutputStream();
.write(geojsonFile.getBytes());
os.flush();
os
// 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) {
.write(buffer, 0, bytesRead);
fos}
}
System.out.println("The raster file it was saved correctly: " + rasterFilePath);
} else {
System.out.println("An error occured: " + conn.getResponseMessage());
}
.disconnect();
conn} catch (IOException e) {
.printStackTrace();
e}
}
}
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
= "https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMgeojson"
url
# Set the useremail & Password
="email"
USEREMAIL="password"
APIKEY
# Path to the GeoJSON file
= "county.geojson"
file_path_to_geojson
# Read the GeoJSON file contents
with open(file_path_to_geojson, "r") as file:
= file.read()
geojson_data
# Set the headers for the request
= {
headers "Content-Type": "application/json"
}
# Make the POST request with the GeoJSON data as the request body
= requests.post(url,
response =geojson_data,
data=headers,
headers=HTTPBasicAuth(USEREMAIL, APIKEY))
auth
= bytes(response.content)
b
with fiona.BytesCollection(b) as f:
= f.crs
crs = gpd.GeoDataFrame.from_features(f, crs=crs)
gdf
# Visualize the data
"Data_2023.07.19") gdf.explore(
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
= paste0("https://www.api.automaticfarmsolutionwebapp.com/AFS/DEMgeojson?")
url
# Set the useremail & Password
="useremail"
USEREMAIL="apikey"
APIKEY
# Path to the GeoJSON file
= "county.geojson"
file_path_to_geojson
# Get the start time to API Call
tic()
# Make the POST request
<- POST(
api_call
url,::authenticate(
httruser = 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
<- content(api_call, as = "text", type = "application/geo+json")
vegetation_index <-geojson_sp(vegetation_index)
vegetation_indexmapview(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