Core‐API‐Reference - Black-Lights/planetscope-py GitHub Wiki

Complete reference documentation for planetscope-py library core components.

Package Overview

import planetscope_py as psp

# Available in planetscope_py.__all__:
from planetscope_py import (
    PlanetAuth,           # Authentication management
    PlanetScopeConfig,    # Configuration management  
    PlanetScopeError,     # Base exception class
    AuthenticationError,  # Authentication exceptions
    ValidationError,      # Input validation exceptions
    RateLimitError,       # Rate limit exceptions
    APIError,            # API communication exceptions
)

Authentication Classes

PlanetAuth

Main authentication class for Planet API access.

class PlanetAuth:
    """Authentication manager for Planet Data API."""
    
    def __init__(
        self, 
        api_key: Optional[str] = None,
        config: Optional[PlanetScopeConfig] = None
    ):
        """Initialize authentication.
        
        Args:
            api_key: Direct API key (highest priority)
            config: Configuration instance (optional)
            
        Raises:
            AuthenticationError: If no valid API key found
        """

Methods

get_session() -> requests.Session

def get_session(self) -> requests.Session:
    """Get authenticated requests session with retry logic.
    
    Returns:
        Configured requests.Session with authentication and retry handling
        
    Example:
        auth = PlanetAuth()
        session = auth.get_session()
        response = session.get("https://api.planet.com/data/v1/")
    """

get_auth_tuple() -> Tuple[str, str]

def get_auth_tuple(self) -> Tuple[str, str]:
    """Get authentication tuple for requests.
    
    Returns:
        Tuple of (api_key, empty_password) for HTTPBasicAuth
        
    Example:
        username, password = auth.get_auth_tuple()
        response = requests.get(url, auth=(username, password))
    """

refresh_session() -> requests.Session

def refresh_session(self) -> requests.Session:
    """Refresh the session (create new one).
    
    Returns:
        New authenticated session
        
    Example:
        # Useful for long-running applications
        new_session = auth.refresh_session()
    """

Properties

api_key -> str

@property
def api_key(self) -> str:
    """Get the API key (masked for security).
    
    Returns:
        Masked API key string for logging/debugging
        
    Example:
        print(auth.api_key)  # Output: PLAK****...****xxxx
    """

is_authenticated -> bool

@property
def is_authenticated(self) -> bool:
    """Check if authentication is valid.
    
    Returns:
        True if API key is available and validated
    """

Configuration Classes

PlanetScopeConfig

Configuration management with multi-source support.

class PlanetScopeConfig:
    """Configuration manager for planetscope-py."""
    
    def __init__(self, config_file: Optional[Union[str, Path]] = None):
        """Initialize configuration.
        
        Args:
            config_file: Path to custom configuration file (optional)
        """

Class Attributes

# Planet API Configuration
BASE_URL = "https://api.planet.com/data/v1"
TILE_URL = "https://tiles.planet.com/data/v1"

# Default search parameters
DEFAULT_ITEM_TYPES = ["PSScene"]
DEFAULT_ASSET_TYPES = ["ortho_analytic_4b", "ortho_analytic_4b_xml"]

# Rate limits (requests per second)
RATE_LIMITS = {
    "search": 10, 
    "activate": 5, 
    "download": 15, 
    "general": 10
}

# Request timeout settings (seconds)
TIMEOUTS = {
    "connect": 10.0,
    "read": 30.0,
    "activation_poll": 300.0,
    "download": 3600.0,
}

# Retry configuration
MAX_RETRIES = 3
BACKOFF_FACTOR = 1.0

# Geometry validation limits
MAX_ROI_AREA_KM2 = 10000
MAX_GEOMETRY_VERTICES = 1000

# Default output settings
DEFAULT_OUTPUT_FORMAT = "GeoTIFF"
DEFAULT_CRS = "EPSG:4326"

Methods

get(key: str, default=None)

def get(self, key: str, default=None):
    """Get configuration value.
    
    Args:
        key: Configuration key
        default: Default value if key not found
        
    Returns:
        Configuration value or default
        
    Example:
        config = PlanetScopeConfig()
        max_retries = config.get('max_retries', 3)
    """

set(key: str, value) -> None

def set(self, key: str, value) -> None:
    """Set configuration value.
    
    Args:
        key: Configuration key
        value: Configuration value
        
    Example:
        config.set('max_retries', 5)
        config.set('max_roi_area_km2', 15000)
    """

to_dict() -> Dict

def to_dict(self) -> Dict:
    """Export configuration as dictionary.
    
    Returns:
        Dictionary containing all configuration values
        
    Example:
        config_dict = config.to_dict()
        print(config_dict['base_url'])
    """

Properties

base_url -> str

@property
def base_url(self) -> str:
    """Get Planet Data API base URL."""

item_types -> List[str]

@property  
def item_types(self) -> List[str]:
    """Get default item types."""

asset_types -> List[str]

@property
def asset_types(self) -> List[str]:
    """Get default asset types."""

rate_limits -> Dict[str, int]

@property
def rate_limits(self) -> Dict[str, int]:
    """Get API rate limits."""

timeouts -> Dict[str, float]

@property
def timeouts(self) -> Dict[str, float]:
    """Get request timeouts."""

Exception Classes

Base Exception

PlanetScopeError

class PlanetScopeError(Exception):
    """Base exception class for all planetscope-py errors.
    
    Args:
        message: Human-readable error description
        details: Optional dictionary with additional error context
    """
    
    def __init__(self, message: str, details: Optional[Dict[str, Any]] = None):
        super().__init__(message)
        self.message = message
        self.details = details or {}

Specific Exceptions

AuthenticationError

class AuthenticationError(PlanetScopeError):
    """Raised when API authentication fails.
    
    This occurs when:
    - No API key is found (env var, config file, or parameter)
    - API key is invalid or expired
    - API key lacks required permissions
    """

ValidationError

class ValidationError(PlanetScopeError):
    """Raised when input validation fails.
    
    This occurs when:
    - Invalid GeoJSON geometry provided
    - Date ranges are malformed or invalid
    - Parameters are outside acceptable ranges
    - ROI size exceeds limits
    """

RateLimitError

class RateLimitError(PlanetScopeError):
    """Raised when API rate limits are exceeded.
    
    Planet API rate limits (per API key):
    - General endpoints: 10 requests/second
    - Activation endpoints: 5 requests/second
    - Download endpoints: 15 requests/second
    """

APIError

class APIError(PlanetScopeError):
    """Raised when Planet API returns an error.
    
    This covers HTTP errors, server errors, and API-specific errors
    that aren't authentication or rate limiting issues.
    """

ConfigurationError

class ConfigurationError(PlanetScopeError):
    """Raised when configuration is invalid or missing.
    
    This occurs when:
    - Configuration files are malformed
    - Required settings are missing
    - Invalid configuration values provided
    """

AssetError

class AssetError(PlanetScopeError):
    """Raised when asset operations fail.
    
    This occurs when:
    - Asset activation fails or times out
    - Requested asset type not available
    - Download permissions insufficient
    """

Utility Functions

All utility functions are available in planetscope_py.utils:

from planetscope_py.utils import (
    validate_geometry,
    validate_date_range,
    validate_roi_size,
    validate_cloud_cover,
    validate_item_types,
    format_api_url,
    calculate_geometry_bounds,
    create_point_geometry,
    create_bbox_geometry,
    pretty_print_json,
    mask_api_key
)

Geometry Functions

validate_geometry(geometry: Dict[str, Any]) -> Dict[str, Any]

def validate_geometry(geometry: Dict[str, Any]) -> Dict[str, Any]:
    """Validate GeoJSON geometry object.
    
    Args:
        geometry: GeoJSON geometry dictionary
        
    Returns:
        Validated and normalized geometry
        
    Raises:
        ValidationError: If geometry is invalid
        
    Example:
        valid_geom = validate_geometry({
            "type": "Polygon", 
            "coordinates": [[lon1, lat1], [lon2, lat2], ...](/Black-Lights/planetscope-py/wiki/[lon1,-lat1],-[lon2,-lat2],-...)
        })
    """

validate_roi_size(geometry: Dict[str, Any]) -> float

def validate_roi_size(geometry: Dict[str, Any]) -> float:
    """Validate ROI size is within acceptable limits.
    
    Args:
        geometry: GeoJSON geometry object
        
    Returns:
        Area in square kilometers
        
    Raises:
        ValidationError: If ROI is too large
        
    Example:
        area_km2 = validate_roi_size(polygon_geometry)
        print(f"ROI area: {area_km2:.2f} km²")
    """

calculate_geometry_bounds(geometry: Dict[str, Any]) -> Tuple[float, float, float, float]

def calculate_geometry_bounds(geometry: Dict[str, Any]) -> Tuple[float, float, float, float]:
    """Calculate bounding box of geometry.
    
    Args:
        geometry: GeoJSON geometry object
        
    Returns:
        Tuple of (min_lon, min_lat, max_lon, max_lat)
        
    Example:
        bounds = calculate_geometry_bounds(polygon_geometry)
        min_lon, min_lat, max_lon, max_lat = bounds
    """

create_point_geometry(longitude: float, latitude: float) -> Dict[str, Any]

def create_point_geometry(longitude: float, latitude: float) -> Dict[str, Any]:
    """Create GeoJSON Point geometry.
    
    Args:
        longitude: Longitude coordinate
        latitude: Latitude coordinate
        
    Returns:
        GeoJSON Point geometry
        
    Example:
        point = create_point_geometry(-122.4194, 37.7749)  # San Francisco
    """

create_bbox_geometry(min_lon: float, min_lat: float, max_lon: float, max_lat: float) -> Dict[str, Any]

def create_bbox_geometry(
    min_lon: float, min_lat: float, max_lon: float, max_lat: float
) -> Dict[str, Any]:
    """Create GeoJSON Polygon from bounding box.
    
    Args:
        min_lon: Minimum longitude
        min_lat: Minimum latitude  
        max_lon: Maximum longitude
        max_lat: Maximum latitude
        
    Returns:
        GeoJSON Polygon geometry
        
    Example:
        bbox = create_bbox_geometry(-122.5, 37.7, -122.3, 37.8)
    """

Date and Time Functions

validate_date_range(start_date: Union[str, datetime], end_date: Union[str, datetime]) -> Tuple[str, str]

def validate_date_range(
    start_date: Union[str, datetime], 
    end_date: Union[str, datetime]
) -> Tuple[str, str]:
    """Validate and normalize date range for Planet API.
    
    Args:
        start_date: Start date (ISO string or datetime object)
        end_date: End date (ISO string or datetime object)
        
    Returns:
        Tuple of (start_iso, end_iso) in Planet API format
        
    Raises:
        ValidationError: If dates are invalid or in wrong order
        
    Example:
        start, end = validate_date_range("2025-01-01", "2025-12-31")
        # Returns: ("2025-01-01T00:00:00.000000Z", "2025-12-31T00:00:00.000000Z")
    """

Parameter Validation Functions

validate_cloud_cover(cloud_cover: Union[float, int]) -> float

def validate_cloud_cover(cloud_cover: Union[float, int]) -> float:
    """Validate cloud cover percentage.
    
    Args:
        cloud_cover: Cloud cover as percentage (0-100) or fraction (0-1)
        
    Returns:
        Normalized cloud cover as fraction (0-1)
        
    Raises:
        ValidationError: If cloud cover is invalid
        
    Example:
        cloud_cover = validate_cloud_cover(15)  # 15% -> 0.15
        cloud_cover = validate_cloud_cover(0.2)  # 0.2 -> 0.2
    """

validate_item_types(item_types: List[str]) -> List[str]

def validate_item_types(item_types: List[str]) -> List[str]:
    """Validate Planet item types.
    
    Args:
        item_types: List of Planet item type strings
        
    Returns:
        Validated item types
        
    Raises:
        ValidationError: If item types are invalid
        
    Valid Types:
        PSScene, REOrthoTile, REScene, PSOrthoTile, SkySatScene,
        SkySatCollect, Landsat8L1G, Sentinel2L1C, MOD09GQ, MYD09GQ,
        MOD09GA, MYD09GA
        
    Example:
        types = validate_item_types(["PSScene", "REOrthoTile"])
    """

Utility Functions

format_api_url(base_url: str, endpoint: str, **params) -> str

def format_api_url(base_url: str, endpoint: str, **params) -> str:
    """Format Planet API URL with parameters.
    
    Args:
        base_url: Base API URL
        endpoint: API endpoint path
        **params: URL parameters
        
    Returns:
        Formatted URL string
        
    Example:
        url = format_api_url(
            "https://api.planet.com/data/v1",
            "item-types/PSScene/items",
            limit=100,
            intersects=geometry
        )
    """

pretty_print_json(data: Any) -> str

def pretty_print_json(data: Any) -> str:
    """Pretty print JSON data.
    
    Args:
        data: Data to format as JSON
        
    Returns:
        Formatted JSON string
        
    Example:
        formatted = pretty_print_json({"key": "value", "nested": {"a": 1}})
        print(formatted)
    """

mask_api_key(api_key: str) -> str

def mask_api_key(api_key: str) -> str:
    """Mask API key for safe logging.
    
    Args:
        api_key: API key to mask
        
    Returns:
        Masked API key string
        
    Example:
        masked = mask_api_key("PLAKabcd1234efgh5678ijkl")
        print(masked)  # Output: PLAKabcd****ijkl
    """

Usage Examples

Complete Authentication Example

from planetscope_py import PlanetAuth, PlanetScopeConfig
from planetscope_py.exceptions import AuthenticationError

try:
    # Initialize with auto-detection
    auth = PlanetAuth()
    
    # Or with explicit configuration
    config = PlanetScopeConfig()
    config.set('max_retries', 5)
    auth = PlanetAuth(config=config)
    
    # Get session and make requests
    session = auth.get_session()
    response = session.get("https://api.planet.com/data/v1/")
    
    print(f" Authentication successful")
    print(f"   API Key: {auth.api_key}")
    print(f"   Status: {response.status_code}")
    
except AuthenticationError as e:
    print(f" Authentication failed: {e.message}")
    for method in e.details.get('methods', []):
        print(f"   Try: {method}")

Complete Validation Example

from planetscope_py.utils import (
    validate_geometry, validate_date_range, validate_cloud_cover
)
from planetscope_py.exceptions import ValidationError

try:
    # Validate geometry
    geometry = {
        "type": "Polygon",
        "coordinates": [[[-122.5, 37.7], [-122.3, 37.7], 
                         [-122.3, 37.8], [-122.5, 37.8], [-122.5, 37.7]]]
    }
    valid_geom = validate_geometry(geometry)
    
    # Validate date range
    start, end = validate_date_range("2025-01-01", "2025-12-31")
    
    # Validate cloud cover
    cloud_cover = validate_cloud_cover(15)  # 15% -> 0.15
    
    print(" All validation passed")
    print(f"   Geometry: {valid_geom['type']}")
    print(f"   Date range: {start} to {end}")
    print(f"   Cloud cover: {cloud_cover}")
    
except ValidationError as e:
    print(f" Validation failed: {e.message}")
    print(f"   Details: {e.details}")

Error Handling Patterns

Comprehensive Error Handling

from planetscope_py.exceptions import (
    PlanetScopeError, AuthenticationError, ValidationError, 
    ConfigurationError, RateLimitError, APIError
)

def robust_planetscope_operation():
    try:
        # Your planetscope-py operations here
        auth = PlanetAuth()
        config = PlanetScopeConfig()
        # ... more operations
        
    except AuthenticationError as e:
        print(f" Authentication issue: {e.message}")
        print("   Check your API key configuration")
        
    except ValidationError as e:
        print(f" Input validation failed: {e.message}")
        print(f"   Error details: {e.details}")
        
    except ConfigurationError as e:
        print(f"  Configuration issue: {e.message}")
        print(f"   File: {e.details.get('file', 'Unknown')}")
        
    except RateLimitError as e:
        print(f" Rate limit exceeded: {e.message}")
        retry_after = e.details.get('retry_after', 60)
        print(f"   Retry after: {retry_after} seconds")
        
    except APIError as e:
        print(f" API communication error: {e.message}")
        status_code = e.details.get('status_code', 'Unknown')
        print(f"   Status code: {status_code}")
        
    except PlanetScopeError as e:
        print(f" General planetscope-py error: {e.message}")
        print(f"   Details: {e.details}")
        
    except Exception as e:
        print(f" Unexpected error: {e}")

Validation Error Context

from planetscope_py.utils import validate_geometry
from planetscope_py.exceptions import ValidationError

def validate_user_input(user_geometry):
    try:
        return validate_geometry(user_geometry)
    except ValidationError as e:
        # Extract specific error information
        error_type = e.details.get('error', 'Unknown validation error')
        
        if "coordinates" in error_type.lower():
            print(" Coordinate issue:")
            bounds = e.details.get('bounds')
            if bounds:
                print(f"   Bounds: {bounds}")
                print("   Ensure coordinates are in [-180,180] for longitude, [-90,90] for latitude")
                
        elif "closed" in error_type.lower():
            print(" Polygon not closed:")
            first = e.details.get('first')
            last = e.details.get('last')
            print(f"   First coordinate: {first}")
            print(f"   Last coordinate: {last}")
            print("   Ensure first and last coordinates are identical")
            
        elif "vertices" in error_type.lower():
            vertex_count = e.details.get('vertex_count', 0)
            max_vertices = e.details.get('max_vertices', 1000)
            print(f" Too many vertices: {vertex_count} > {max_vertices}")
            print("   Simplify your geometry or split into smaller polygons")
            
        raise  # Re-raise for calling code to handle

Constants and Enumerations

Planet API Constants

# Available through PlanetScopeConfig class attributes
BASE_URL = "https://api.planet.com/data/v1"
TILE_URL = "https://tiles.planet.com/data/v1"

# Item Types (for validation)
VALID_ITEM_TYPES = {
    "PSScene",           # PlanetScope imagery
    "REOrthoTile",       # RapidEye ortho tiles  
    "REScene",           # RapidEye scenes
    "PSOrthoTile",       # PlanetScope ortho tiles
    "SkySatScene",       # SkySat scenes
    "SkySatCollect",     # SkySat collections
    "Landsat8L1G",       # Landsat 8 scenes
    "Sentinel2L1C",      # Sentinel-2 scenes
    "MOD09GQ",           # MODIS Terra daily
    "MYD09GQ",           # MODIS Aqua daily
    "MOD09GA",           # MODIS Terra daily global
    "MYD09GA",           # MODIS Aqua daily global
}

# Rate Limits (requests per second)
RATE_LIMITS = {
    "search": 10,        # Search/query operations
    "activate": 5,       # Asset activation
    "download": 15,      # Asset downloads
    "general": 10,       # General API operations
}

# Timeout Settings (seconds)
TIMEOUTS = {
    "connect": 10.0,     # Connection timeout
    "read": 30.0,        # Read timeout
    "activation_poll": 300.0,  # Asset activation polling
    "download": 3600.0,  # Large file downloads
}

Validation Limits

# Geometry validation limits
MAX_ROI_AREA_KM2 = 10000         # Maximum ROI area (10,000 km²)
MAX_GEOMETRY_VERTICES = 1000     # Maximum polygon vertices
DEFAULT_CRS = "EPSG:4326"        # Default coordinate reference system

# Coordinate bounds (WGS84)
MIN_LONGITUDE = -180.0
MAX_LONGITUDE = 180.0
MIN_LATITUDE = -90.0
MAX_LATITUDE = 90.0

# Cloud cover validation
MIN_CLOUD_COVER = 0.0           # 0%
MAX_CLOUD_COVER = 1.0           # 100%

Type Definitions

planetscope-py uses progressive type hints. Here are the main type definitions:

from typing import Dict, List, Tuple, Union, Optional, Any
from datetime import datetime
from pathlib import Path

# Geometry types
GeometryDict = Dict[str, Any]  # GeoJSON geometry
CoordinateType = Union[List[float], Tuple[float, float]]
BoundsType = Tuple[float, float, float, float]  # (min_lon, min_lat, max_lon, max_lat)

# Date types  
DateType = Union[str, datetime]
DateRangeType = Tuple[str, str]  # (start_iso, end_iso)

# Configuration types
ConfigDict = Dict[str, Any]
ConfigPath = Union[str, Path]

# API types
ApiKeyType = str
UrlType = str
HeadersType = Dict[str, str]
ParamsType = Dict[str, Any]

# Error types
ErrorDetailsType = Dict[str, Any]

Environment Variables

planetscope-py recognizes these environment variables:

# Authentication
PL_API_KEY = "your_planet_api_key"      # Planet API key

# Configuration overrides
PLANETSCOPE_BASE_URL = "https://api.planet.com/data/v1"
PLANETSCOPE_MAX_RETRIES = "3" 
PLANETSCOPE_MAX_ROI_AREA = "10000"      # km²
PLANETSCOPE_DEFAULT_CRS = "EPSG:4326"
PLANETSCOPE_LOG_LEVEL = "INFO"          # DEBUG, INFO, WARNING, ERROR

# Development/testing
PLANETSCOPE_CACHE_DIR = "/path/to/cache"
PLANETSCOPE_CONFIG_FILE = "/path/to/config.json"

Configuration File Format

~/.planet.json Schema

{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "properties": {
        "api_key": {
            "type": "string",
            "description": "Planet API key",
            "pattern": "^PLAK[A-Za-z0-9]+$"
        },
        "base_url": {
            "type": "string",
            "format": "uri",
            "default": "https://api.planet.com/data/v1"
        },
        "max_retries": {
            "type": "integer",
            "minimum": 0,
            "maximum": 10,
            "default": 3
        },
        "max_roi_area_km2": {
            "type": "number",
            "minimum": 1,
            "maximum": 100000,
            "default": 10000
        },
        "default_crs": {
            "type": "string",
            "pattern": "^EPSG:[0-9]+$",
            "default": "EPSG:4326"
        },
        "timeouts": {
            "type": "object",
            "properties": {
                "connect": {"type": "number", "minimum": 1},
                "read": {"type": "number", "minimum": 1},
                "activation_poll": {"type": "number", "minimum": 60},
                "download": {"type": "number", "minimum": 300}
            }
        },
        "rate_limits": {
            "type": "object",
            "properties": {
                "search": {"type": "integer", "minimum": 1},
                "activate": {"type": "integer", "minimum": 1}, 
                "download": {"type": "integer", "minimum": 1},
                "general": {"type": "integer", "minimum": 1}
            }
        }
    },
    "required": ["api_key"]
}

Example Configuration Files

Minimal Configuration:

{
    "api_key": "PLAKxxxxxxxxxxxxxxxxxxxxxxxx"
}

Advanced Configuration:

{
    "api_key": "PLAKxxxxxxxxxxxxxxxxxxxxxxxx",
    "base_url": "https://api.planet.com/data/v1",
    "max_retries": 5,
    "max_roi_area_km2": 15000,
    "default_crs": "EPSG:4326",
    "timeouts": {
        "connect": 15.0,
        "read": 45.0,
        "activation_poll": 600.0,
        "download": 7200.0
    },
    "rate_limits": {
        "search": 15,
        "activate": 8,
        "download": 20,
        "general": 12
    }
}

Testing Utilities

For testing and development, planetscope-py provides several utilities:

Mock Authentication

# For testing without real API key
from planetscope_py import PlanetAuth
from unittest.mock import patch

with patch.object(PlanetAuth, '_validate_api_key'):
    auth = PlanetAuth(api_key="test_key")
    # auth.is_authenticated will be True for testing

Configuration Testing

# Test custom configuration
from planetscope_py import PlanetScopeConfig
import tempfile
import json

config_data = {
    "api_key": "test_key",
    "max_retries": 5,
    "base_url": "https://test.example.com"
}

with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
    json.dump(config_data, f)
    config_file = f.name

config = PlanetScopeConfig(config_file=config_file)
assert config.get('max_retries') == 5

Validation Testing

# Test validation functions
from planetscope_py.utils import validate_geometry
from planetscope_py.exceptions import ValidationError

# Test valid geometry
valid_poly = {
    "type": "Polygon", 
    "coordinates": [[-1, -1], [1, -1], [1, 1], [-1, 1], [-1, -1](/Black-Lights/planetscope-py/wiki/[-1,--1],-[1,--1],-[1,-1],-[-1,-1],-[-1,--1)]
}
assert validate_geometry(valid_poly) == valid_poly

# Test invalid geometry
invalid_poly = {"type": "Invalid"}
try:
    validate_geometry(invalid_poly)
    assert False, "Should have raised ValidationError"
except ValidationError:
    pass  # Expected

Migration Guide

From Other Planet Libraries

If migrating from other Planet API libraries, here are the key differences:

From planet-client-python:

# Old way (planet-client-python)
from planet import api
client = api.ClientV1(api_key="key")

# New way (planetscope-py)
from planetscope_py import PlanetAuth
auth = PlanetAuth(api_key="key")
session = auth.get_session()

Authentication Pattern Changes:

# Old pattern
import os
api_key = os.environ['PL_API_KEY']
client = SomeClient(api_key)

# planetscope-py pattern  
from planetscope_py import PlanetAuth
auth = PlanetAuth()  # Auto-detects PL_API_KEY
session = auth.get_session()

Performance Considerations

Session Reuse

#  Good: Reuse session
auth = PlanetAuth()
session = auth.get_session()

for i in range(100):
    response = session.get(f"https://api.planet.com/data/v1/endpoint/{i}")

#  Bad: Create new session each time
for i in range(100):
    auth = PlanetAuth()  # Expensive validation each time
    session = auth.get_session()
    response = session.get(f"https://api.planet.com/data/v1/endpoint/{i}")

Configuration Caching

#  Good: Reuse configuration
config = PlanetScopeConfig()
auth1 = PlanetAuth(config=config)
auth2 = PlanetAuth(config=config)

#  Less efficient: Create config each time
auth1 = PlanetAuth()  # Creates new config
auth2 = PlanetAuth()  # Creates new config

Geometry Validation Optimization

#  Good: Validate once, reuse
validated_geom = validate_geometry(user_input_geometry)
area = validate_roi_size(validated_geom)
bounds = calculate_geometry_bounds(validated_geom)

#  Less efficient: Multiple validations
area = validate_roi_size(user_input_geometry)  # Validates geometry
bounds = calculate_geometry_bounds(user_input_geometry)  # Validates again

Version Information

import planetscope_py

# Package version
print(planetscope_py.__version__)        # "0.1.0-dev"
print(planetscope_py.__version_info__)   # (0, 1, 0, "dev")

# Author information
print(planetscope_py.__author__)         # "Ammar & Umayr"
print(planetscope_py.__email__)          # "[email protected]"
print(planetscope_py.__url__)            # "https://github.com/Black-Lights/planetscope-py"

Next Steps

This API reference covers all Phase 1 components. As development progresses:

  • Phase 2: Planet API Integration classes and functions
  • Phase 3: Spatial analysis engine and density calculation methods
  • Phase 4: Temporal analysis and grid compatibility functions
  • Phase 5: Output management and export utilities

Stay updated with the latest API additions in the project documentation.