Download API using subscription id

I have a single collection with several subscription id and I am wondering how can I filter images based on subscription id and name in the below code:

import os
import json
import requests
from datetime import datetime

bbox = [25.526527436, 60.349350476, 25.552590162, 60.36519386]
collection_id = <"e40b4a3f-c192-43e7-85af-466e265dd6ed">
subscription_id = <"00587bab-6286-479f-b521-4dff9885f116">
subscription_name = "karleby2023"
time_period = "2023-05-01T00:00:00Z/2023-10-01T23:59:59Z"
out_dir = '/content/'

# Your Sentinel Hub client ID and client secret
CLIENT_ID = '*****'
CLIENT_SECRET = '****'

# Define the OAuth2 token URL
token_url = 'https://services.sentinel-hub.com/oauth/token'

# Define the headers and payload for the token request
token_headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
}

token_payload = {
    'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET
}

# Request the access token
token_response = requests.post(token_url, headers=token_headers, data=token_payload)

# Check if the token request was successful
if token_response.status_code == 200:
    access_token = token_response.json().get('access_token')
else:
    print(f"Failed to obtain access token: {token_response.status_code}")
    print(token_response.text)
    exit()

catalog_endpoint = 'https://services.sentinel-hub.com/api/v1/catalog/search'

catalog_headers = {
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {access_token}'
}

catalog_payload = {
    "bbox": bbox,  # bbox = [min_x, min_y, max_x, max_y]
    "datetime": time_period,  # Updated date range
    "collections": ["byoc-"+collection_id],  # Use the specific sub-collection ID
    "limit": 20  # Adjust as necessary to cover the expected number of images
}

catalog_response = requests.post(catalog_endpoint, headers=catalog_headers, data=json.dumps(catalog_payload))

if catalog_response.status_code == 200:
    features = catalog_response.json().get('features', [])
else:
    print(f"Failed to list available images: {catalog_response.status_code}")
    print(catalog_response.text)
    exit()

output_dir = out_dir
os.makedirs(output_dir, exist_ok=True)

process_endpoint = 'https://services.sentinel-hub.com/api/v1/process'

process_headers = {
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {access_token}'
}

# Define the evalscript
evalscript = """
//VERSION=3
function setup() {
    return {
        input: [{"bands": ["nir", "red"]}],
        output: {
            bands: 1,
            sampleType: "FLOAT32"
        }
    };
}

function evaluatePixel(sample) {
  let ndvi = (sample.nir - sample.red) / (sample.nir + sample.red);
  return [ndvi];
}
"""

# Iterate over the list of available images and download each one
for i, feature in enumerate(features):
    print(f"Downloading image {i + 1} of {len(features)}")
    feature_id = feature['id']
    acquisition_date = feature['properties']['datetime']  # Extract the acquisition date
    feature_name = datetime.strptime(acquisition_date, "%Y-%m-%dT%H:%M:%S.%fZ").strftime('%Y%m%d_%H%M%S')  # Format the acquisition date

    # Define your area of interest (AOI) and other parameters
    request_payload = {
        "input": {
            "bounds": {
                "bbox": bbox  # bbox = [min_x, min_y, max_x, max_y]
            },
            "data": [
                {
                    "type": "byoc-"+collection_id,  # Use the specific sub-collection ID
                    "dataFilter": {
                        "timeRange": {
                            "from": acquisition_date,
                            "to": acquisition_date
                        }
                    }
                }
            ]
        },
        "evalscript": evalscript,
        "output": {
            "responses": [
                {
                    "identifier": "default",
                    "format": {
                        "type": "image/tiff"
                    }
                }
            ]
        }
    }

    # Make the API request
    process_response = requests.post(process_endpoint, headers=process_headers, data=json.dumps(request_payload))

    # Check if the request was successful
    if process_response.status_code == 200:
        # Save the response content to a file using the acquisition date as the file name
        image_path = os.path.join(output_dir, f'{feature_name}.tiff')
        with open(image_path, 'wb') as f:
            f.write(process_response.content)
        print(f"Image {i + 1} saved successfully as {feature_name}.tiff.")
    else:
        print(f"Failed to download image {i + 1}: {process_response.status_code}")
        print(process_response.text)

Hi!

Based on your question, we are opening a Planet Support ticket on your behalf. We will follow up directly via email.

Hi,
I am waiting more than 3 days to get a response from support service through email. The ticket is made without any response to the question. Would you please rush my request. The project stopped because of this issue. looking forward to hearing form support service.
Sincerely

Hi was there an answer to this question?

No. I haven’t received answer.

Hi Amirhossein,

Due to the nature of your request we answered via a support ticket, which was sent to you on 24 June from the Planet technical support team. Happy to forward you the email thread that you participated in just in case you have deleted the email already.

In the public interest, I’m happy to post our response to this query:

In your workflow, you are trying to use the Catalog API to find all the tiles that have been delivered into the collection and then process them with an evalscript using the Processing API.

The tiles unfortunately do not come with the metadata related to the subscription, so it would be difficult to separate them based on this information, but they do have the subscription ID in their name. To filter out the tiles based on subscriptions, you might have to define your own function that reads in the name of the tile, parses out the subscription ID, compares it with a list of the subscription IDs (which you might have to manually define) and segregates them.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.