Authentication Guide - Black-Lights/planetscope-py GitHub Wiki
This guide covers all aspects of authentication with planetscope-py, from basic setup to advanced configuration options.
Overview
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.
Authentication Priority Order
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
Method 1: Environment Variable (Recommended)
The most secure and convenient method for most users.
Setup Instructions
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 ~/.zshrc
Windows 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")
Verification
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}")
Method 2: Configuration File
Perfect for persistent local development environments.
Create Configuration File
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 |
File Content
{
"api_key": "your_planet_api_key_here"
}
Quick Creation Commands
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
Advanced Configuration
{
"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"
}
Verification
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}")
Method 3: Direct Parameter
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)
Getting Your Planet API Key
Step 1: Create Planet Account
- Visit [Planet Labs](https://www.planet.com/)
- Sign up for an account or log in
- Navigate to [Account Settings](https://www.planet.com/account/#/)
Step 2: Generate API Key
- Go to the "API Keys" section
- Click "Create New API Key"
- Copy your API key (starts with
PLAKxxxxx
)
Step 3: Verify Access
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}")
Advanced Authentication Features
Session Management
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}")
Authentication Tuple
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)
)
Session Refresh
# Refresh session if needed
new_session = auth.refresh_session()
# Useful for long-running applications
# or when session state becomes invalid
Security Best Practices
1. API Key Protection
# DO: Use environment variables
export PL_API_KEY="PLAKxxxxx"
# DON'T: Hardcode in scripts
api_key = "PLAKxxxxx" # Never do this!
2. Configuration File Security
# Set proper permissions on config file
chmod 600 ~/.planet.json
# Verify permissions
ls -la ~/.planet.json
# Should show: -rw------- (owner read/write only)
3. Version Control
# Add to .gitignore
echo "*.json" >> .gitignore
echo ".env" >> .gitignore
echo "**/config.json" >> .gitignore
4. Credential Masking
planetscope-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 details
Troubleshooting
Common Authentication Errors
Error: "No Planet API key found"
from 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_KEY
environment variable - Create
~/.planet.json
config file - Pass
api_key
parameter directly
Error: "Invalid Planet API key"
# 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
Error: Network/Connection Issues
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}")
Debugging Authentication
Check Authentication Status
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}")
Verbose Error Information
import logging
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
# Authentication will now show detailed information
auth = PlanetAuth()
Environment-Specific Setup
Development Environment
# 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()
Production Environment
# Use system environment variables
export PL_API_KEY="your_production_api_key"
export PLANETSCOPE_LOG_LEVEL="INFO"
export PLANETSCOPE_MAX_RETRIES="3"
Docker Environment
# 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
Testing Authentication
Quick Test Script
#!/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'}")
Next Steps
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