-
Notifications
You must be signed in to change notification settings - Fork 0
Authentication Guide
This guide covers all aspects of authentication with planetscope-py, from basic setup to advanced configuration options.
planetscope-py uses a hierarchical authentication system that automatically discovers your Planet API key from multiple sources. The system prioritizes security and convenience while providing flexible configuration options.
The authentication system checks for credentials in this order:
- Direct Parameter (Highest Priority)
-
Environment Variable (
PL_API_KEY) -
Configuration File (
~/.planet.json) - Error if None Found
The most secure and convenient method for most users.
Linux/macOS (Bash/Zsh):
# Add to your shell profile (~/.bashrc, ~/.zshrc, etc.)
export PL_API_KEY="your_planet_api_key_here"
# Apply immediately
source ~/.bashrc # or ~/.zshrcWindows Command Prompt:
# Set for current session
set PL_API_KEY=your_planet_api_key_here
# Set permanently (requires admin)
setx PL_API_KEY "your_planet_api_key_here"Windows PowerShell:
# Set for current session
$env:PL_API_KEY="your_planet_api_key_here"
# Set permanently
[Environment]::SetEnvironmentVariable("PL_API_KEY", "your_planet_api_key_here", "User")import os
from planetscope_py import PlanetAuth
# Check environment variable
print(f"API Key set: {'PL_API_KEY' in os.environ}")
# Test authentication
auth = PlanetAuth()
print(f"Authentication successful: {auth.is_authenticated}")
print(f"Masked API key: {auth.api_key}")Perfect for persistent local development environments.
Create ~/.planet.json in your home directory:
| Operating System | Configuration Path |
|---|---|
| Linux | /home/username/.planet.json |
| macOS | /Users/username/.planet.json |
| Windows | C:\Users\username\.planet.json |
{
"api_key": "your_planet_api_key_here"
}Windows (PowerShell):
New-Item -Path "$env:USERPROFILE\.planet.json" -ItemType File -Force
notepad "$env:USERPROFILE\.planet.json"Linux/macOS:
touch ~/.planet.json
nano ~/.planet.json{
"api_key": "your_planet_api_key_here",
"base_url": "https://api.planet.com/data/v1",
"max_retries": 3,
"max_roi_area_km2": 10000,
"default_crs": "EPSG:4326"
}from pathlib import Path
import json
# Check if config file exists
config_path = Path.home() / ".planet.json"
print(f"Config file exists: {config_path.exists()}")
# Validate config file
if config_path.exists():
with open(config_path, 'r') as f:
config = json.load(f)
print(f"API key configured: {'api_key' in config}")Useful for scripts, testing, or dynamic environments.
from planetscope_py import PlanetAuth
# Direct API key specification
auth = PlanetAuth(api_key="your_planet_api_key_here")
# With custom configuration
from planetscope_py import PlanetScopeConfig
config = PlanetScopeConfig()
auth = PlanetAuth(api_key="your_api_key", config=config)- Visit [Planet Labs](https://www.planet.com/)
- Sign up for an account or log in
- Navigate to [Account Settings](https://www.planet.com/account/#/)
- Go to the "API Keys" section
- Click "Create New API Key"
- Copy your API key (starts with
PLAKxxxxx)
from planetscope_py import PlanetAuth
# Test your API key
try:
auth = PlanetAuth(api_key="your_api_key_here")
session = auth.get_session()
response = session.get("https://api.planet.com/data/v1/")
if response.status_code == 200:
print("API key is valid!")
print(f"Response: {response.json()}")
else:
print(f"API validation failed: {response.status_code}")
except Exception as e:
print(f"Authentication error: {e}")from planetscope_py import PlanetAuth
auth = PlanetAuth()
# Get authenticated session with retry logic
session = auth.get_session()
# Session includes:
# - Automatic retry on rate limits
# - Proper User-Agent headers
# - Timeout configuration
# - HTTPBasicAuth setup
# Make API requests
response = session.get("https://api.planet.com/data/v1/item-types/")
print(f"Available item types: {response.status_code}")For use with external libraries:
# Get auth tuple for requests
username, password = auth.get_auth_tuple()
# Use with requests directly
import requests
response = requests.get(
"https://api.planet.com/data/v1/",
auth=(username, password)
)# Refresh session if needed
new_session = auth.refresh_session()
# Useful for long-running applications
# or when session state becomes invalid# DO: Use environment variables
export PL_API_KEY="PLAKxxxxx"
# DON'T: Hardcode in scripts
api_key = "PLAKxxxxx" # Never do this!# Set proper permissions on config file
chmod 600 ~/.planet.json
# Verify permissions
ls -la ~/.planet.json
# Should show: -rw------- (owner read/write only)# Add to .gitignore
echo "*.json" >> .gitignore
echo ".env" >> .gitignore
echo "**/config.json" >> .gitignoreplanetscope-py automatically masks credentials in logs:
auth = PlanetAuth()
print(auth.api_key) # Output: PLAK****...****xxxxx (masked)
# API keys are never exposed in:
# - Error messages
# - Log outputs
# - String representations
# - Exception detailsfrom planetscope_py.exceptions import AuthenticationError
try:
auth = PlanetAuth()
except AuthenticationError as e:
print(f"Error: {e.message}")
print("Available methods:")
for method in e.details.get('methods', []):
print(f" - {method}")
print(f"Help: {e.details.get('help_url', 'N/A')}")Solutions:
- Set
PL_API_KEYenvironment variable - Create
~/.planet.jsonconfig file - Pass
api_keyparameter directly
# Check API key format
api_key = "your_key_here"
if not api_key.startswith("PLAK"):
print("API key should start with 'PLAK'")
else:
print("API key format looks correct")Solutions:
- Verify key from Planet account settings
- Check for typos or extra spaces
- Ensure key hasn't expired
- Verify account permissions
from planetscope_py.exceptions import AuthenticationError
try:
auth = PlanetAuth()
except AuthenticationError as e:
if "network error" in str(e):
print("Network issue - check internet connection")
print(f"Details: {e.details}")from planetscope_py import PlanetAuth
auth = PlanetAuth()
print(f"Authenticated: {auth.is_authenticated}")
print(f"API Key (masked): {auth.api_key}")
# Test API connection
session = auth.get_session()
try:
response = session.get("https://api.planet.com/data/v1/", timeout=10)
print(f"API Status: {response.status_code}")
print(f"Rate Limit Remaining: {response.headers.get('X-RateLimit-Remaining', 'Unknown')}")
except Exception as e:
print(f"Connection test failed: {e}")import logging
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
# Authentication will now show detailed information
auth = PlanetAuth()# Use .env file for development
cat > .env << EOF
PL_API_KEY=your_development_api_key
PLANETSCOPE_LOG_LEVEL=DEBUG
PLANETSCOPE_MAX_RETRIES=5
EOF
# Load in Python
from dotenv import load_dotenv
load_dotenv()# Use system environment variables
export PL_API_KEY="your_production_api_key"
export PLANETSCOPE_LOG_LEVEL="INFO"
export PLANETSCOPE_MAX_RETRIES="3"# Dockerfile
FROM python:3.11-slim
# Install planetscope-py
RUN pip install planetscope-py
# Set environment variable
ENV PL_API_KEY=""
# Runtime will need API key:
# docker run -e PL_API_KEY="your_key" your_image#!/usr/bin/env python3
"""
Quick authentication test for planetscope-py
"""
def test_authentication():
try:
from planetscope_py import PlanetAuth
print("Testing planetscope-py authentication...")
# Initialize authentication
auth = PlanetAuth()
print(f"Authentication initialized")
print(f" Authenticated: {auth.is_authenticated}")
print(f" API Key: {auth.api_key}")
# Test API connection
session = auth.get_session()
response = session.get("https://api.planet.com/data/v1/")
if response.status_code == 200:
print(f"API connection successful")
print(f" Status: {response.status_code}")
print(f" Content-Type: {response.headers.get('Content-Type', 'Unknown')}")
return True
else:
print(f"API connection failed: {response.status_code}")
return False
except Exception as e:
print(f"Authentication failed: {e}")
return False
if __name__ == "__main__":
success = test_authentication()
print(f"Test result: {'SUCCESS' if success else 'FAILED'}")Once authentication is configured:
- Explore Core Features: See Phase 1 Foundation
- Try Examples: Check out Tutorials & Examples
- Core API Reference: Browse the Core API Reference
- Planet API Reference: Browse the Planet API Reference
Getting Started
Core Features
- Scene Discovery
- Metadata Analysis
- Spatial Density Analysis and Visualization
- Rate Limiting & Performance
Advanced Analysis
Integration Workflows
Examples & Tutorials
API Reference
Support