Basic retrieval

This page contains end-to-end examples highlighting the capabilities of the Agricultural Understanding API. These examples cover primary workflows for landscape discovery, feature retrieval, and field monitoring.

Prerequisites

To follow this guide, you need:

  • A basic understanding of Python.
  • Familiarity with S2 geometry concepts. See Understanding the data for more information.
  • An API key for the Agricultural Understanding API. See Setup for instructions on how to get an API key.

Retrieve a landscape

Retrieves spatial feature boundaries and polygons for agricultural elements like fields, ponds, and trees. View the lookupLandscape reference documentation for more information.

If you need to look up boundaries for specific past dates, explore the Retrieve historical captures example.

lookupLandscape example

The following Python code sends the API request to the lookupLandscape endpoint and parses the embedded GeoJSON payload to extract alu_type classifications and the area:

import json
import os
import requests

API_KEY = os.environ.get("AG_UNDERSTANDING_API_KEY")
if not API_KEY:
    raise ValueError("Please set the 'AG_UNDERSTANDING_API_KEY' environment variable.")

ENDPOINT_URL = "https://agriculturalunderstanding.googleapis.com/v1:lookupLandscape"

request_body = {
    "locationSpecifier": {
        "s2CellId": "4306523180387794944"
    }
}

response = requests.post(ENDPOINT_URL, json=request_body, params={"key": API_KEY})
response.raise_for_status()
data = response.json()

landscape = data.get("landscape", {})
geojson_str = landscape.get("geojson")

if geojson_str:
    feature_collection = json.loads(geojson_str)
    features = feature_collection.get("features", [])

    print(f"Retrieved {len(features)} landscape features.")
    for feature in features:
        props = feature.get("properties", {})
        alu_type = props.get("alu_type", "Unknown")
        area = props.get("area_sq_m", 0)
        print(f"Feature type: {alu_type}, area: {area} sq m")
else:
    print("No GeoJSON data found in the response.")

Parsed GeoJSON

Because the API response contains a stringified representation of the GeoJSON map payload, your application parses the string to inspect shapes and properties. The parsed payload renders a FeatureCollection structure:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": "7M2JHHF6+MFWC",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
            [
              [92.5612194, 10.5741646], [92.5612194, 10.5742008],
              [92.5612559, 10.5742551], [92.5612467, 10.5742912],
              [92.5612192, 10.5743094], [92.5611644, 10.5743001],
              [92.5611462, 10.5742731], [92.5611462, 10.5742006],
              [92.5611646, 10.5741555], [92.5612194, 10.5741646]
            ]
          ]
        ]
      },
      "properties": {
        "alu_type": "trees",
        "area_sq_m": 149.7001,
        "class_confidence": 1.0,
        "capture_timestamp_sec": 1697353200
      }
    }
  ]
}

Payload breakdown:

  • Stringified GeoJSON: The geojson field is returned as an escaped JSON string.
  • Feature properties: In this example, the returned feature has "alu_type": "trees".
  • Feature ID: The id (7M2JHHF6+MFWC) represents the Plus Code of the feature's centroid.
  • Cross-references: For details on schema characteristics, see Response format.

Monitor crop development on a landscape

Fetches in-season crop predictions and confidence scores for specified fields and time ranges. View the monitorLandscape reference documentation for more information.

monitorLandscape example

The following Python code queries the monitorLandscape endpoint, extracts the nested monitoring data, and iterates over crop prediction timelines:

import json
import os
import requests

API_KEY = os.environ.get("AG_UNDERSTANDING_API_KEY")
if not API_KEY:
    raise ValueError("Please set the 'AG_UNDERSTANDING_API_KEY' environment variable.")

ENDPOINT_URL = "https://agriculturalunderstanding.googleapis.com/v1:monitorLandscape"

request_body = {
    "locationSpecifier": {
        "s2CellId": "4306523180387794944"
    }
}

response = requests.post(ENDPOINT_URL, json=request_body, params={"key": API_KEY})
response.raise_for_status()
data = response.json()

monitored_landscape = data.get("monitoredLandscape", {})
geojson_str = monitored_landscape.get("geojson")

if geojson_str:
    feature_collection = json.loads(geojson_str)
    features = feature_collection.get("features", [])

    print(f"Retrieved {len(features)} features.")

    for feature in features:
        props = feature.get("properties", {})
        feature_id = feature.get("id", "Unknown ID")
        area = props.get("area_sq_m", 0)

        print(f"\nFeature ID: {feature_id} | Area: {area} sq m")

        predictions = props.get("monitoring_prediction", [])
        if not predictions:
            print("  -> No monitoring predictions available.")
            continue

        for pred in predictions:
            start = pred.get("start_timestamp_sec")
            end = pred.get("end_timestamp_sec")
            print(f"  -> Prediction window: {start} to {end}")

            crop_1 = pred.get("crop_1")
            if crop_1 == "NO_PREDICTION":
                print("     No cultivation predicted.")
                continue

            # The API returns up to 3 crop predictions per time window.
            for i in range(1, 4):
                crop_name = pred.get(f"crop_{i}")
                crop_conf = pred.get(f"conf_{i}")

                # Check for existence, as missing/unknown crops might be omitted.
                if crop_name and crop_conf is not None:
                    print(f"     Crop {i}: {crop_name} (Confidence: {crop_conf})")
else:
    print("No GeoJSON data found in the response.")

Parsed monitoring GeoJSON

Parsing the geojson string yields feature data with crop predictions for fields:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": "7M2JHHF6+W4X9",
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
            [
              [92.5603869, 10.5746971], [92.5604233, 10.5747242],
              [92.5603412, 10.5746969], [92.5603869, 10.5746971]
            ]
          ]
        ]
      },
      "properties": {
        "alu_type": "field",
        "area_sq_m": 554.6408,
        "class_confidence": 0.7303,
        "capture_timestamp_sec": 1558422000,
        "monitoring_prediction": [
          {
            "start_timestamp_sec": 1558422000,
            "end_timestamp_sec": 1566370800,
            "crop_1": "WHEAT",
            "conf_1": 0.852,
            "crop_2": "MUSTARD",
            "conf_2": 0.12
          }
        ]
      }
    }
  ]
}

Payload breakdown:

  • Prediction object: Features with an alu_type of field contain seasonal crop predictions in monitoring_prediction.
  • Crop classification: In monitoring_prediction, crop_1 indicates "WHEAT" with confidence score 0.852.
  • Prediction values: crop_x returns the name of the predicted crop. If the model is unable to detect a crop, it may return NO_PREDICTION or UNKNOWN_CROP.
  • Cross-references: See Understanding the data to understand crop monitoring models.