API Reference¶
Complete API reference for the pCloud SDK Python v2.0.
Table of Contents¶
- PCloudSDK Class
- Authentication Methods
- User Operations
- Folder Operations
- File Operations
- Progress Utilities
- Core Classes
- Configuration
- Exception Handling
PCloudSDK Class¶
The main SDK class that provides a convenient wrapper around all pCloud operations with integrated token management.
Constructor¶
PCloudSDK(
app_key: str πΎ"",
app_secret: str πΎ"",
access_token: str πΎ"",
location_id: int πΎ2,
auth_type: str πΎ"direct",
token_manager: bool πΎTrue,
token_file: str πΎ".pcloud_credentials"
)
Parameters:
- app_key (str): Your pCloud app key (Client ID) - optional for direct login
- app_secret (str): Your pCloud app secret (Client Secret) - optional for direct login
- access_token (str): Access token (optional, can be set later)
- location_id (int): Server location (1=US, 2=EU) - default EU
- auth_type (str): Authentication type ("oauth2" or "direct") - default direct
- token_manager (bool): Enable automatic token management (default True)
- token_file (str): File to store credentials (default .pcloud_credentials)
Example:
from pcloud_sdk import PCloudSDK
# Default configuration (recommended)
sdk πΎPCloudSDK()
# Custom configuration
sdk πΎPCloudSDK(
location_id=1, # US servers
token_file=".my_credentials",
auth_type="oauth2"
)
Properties¶
user¶
Returns a User instance for user operations.
folder¶
Returns a Folder instance for folder operations.
file¶
Returns a File instance for file operations.
Authentication Methods¶
login()¶
Login with email/password or use saved credentials.
login(
email: str πΎ"",
password: str πΎ"",
location_id: int πΎ2,
force_login: bool πΎFalse
) -π Dict[str, Any]
Parameters:
- email (str): pCloud email (optional if credentials are saved)
- password (str): pCloud password (optional if credentials are saved)
- location_id (int): Server location (1=US, 2=EU)
- force_login (bool): Force new login even if credentials exist
Returns:
- Dict[str, Any]: Login information including access_token, locationid, email, etc.
Example:
# First time login
login_info πΎsdk.login("user@example.com", "password")
# Subsequent logins (uses saved token)
login_info πΎsdk.login()
# Force new login
login_info πΎsdk.login("user@example.com", "password", force_login=True)
get_auth_url()¶
Get OAuth2 authorization URL.
Parameters:
- redirect_uri (str): Redirect URI for OAuth2 callback
Returns:
- str: Authorization URL
Example:
authenticate()¶
Exchange authorization code for access token.
Parameters:
- code (str): Authorization code from OAuth2 callback
- location_id (int): Server location
Returns:
- Dict[str, Any]: Token information
Example:
set_access_token()¶
Set access token directly.
Parameters:
- access_token (str): Access token
- auth_type (str): Authentication type ("direct" or "oauth2")
is_authenticated()¶
Check if SDK is authenticated.
Returns:
- bool: True if authenticated
logout()¶
Logout and clear credentials.
Token Management Methods¶
clear_saved_credentials()¶
Clear saved credentials file.
get_saved_email()¶
Get the email from saved credentials.
get_credentials_info()¶
Get information about current credentials.
Returns:
- Dict[str, Any]: Credentials information including email, age, location, etc.
User Operations¶
Access via sdk.user property.
get_user_info()¶
Get complete user information.
Returns:
- Dict[str, Any]: Complete user information
Example:
user_info πΎsdk.user.get_user_info()
print(f"Email: {user_info['email']}")
print(f"User ID: {user_info['userid']}")
get_user_id()¶
Get user ID.
Returns:
- int: User ID
get_user_email()¶
Get user email.
Returns:
- str: User email
get_used_quota()¶
Get used quota in bytes.
Returns:
- int: Used quota in bytes
get_quota()¶
Get total quota in bytes.
Returns:
- int: Total quota in bytes
get_public_link_quota()¶
Get public link quota.
Returns:
- int: Public link quota
Folder Operations¶
Access via sdk.folder property.
get_metadata()¶
Get folder metadata.
get_metadata(
folder_id: Optional[int] πΎNone,
path: Optional[str] πΎNone
) -π Dict[str, Any]
Parameters:
- folder_id (Optional[int]): Folder ID
- path (Optional[str]): Folder path
Returns:
- Dict[str, Any]: Folder metadata
list_root()¶
List root folder contents.
Returns:
- Dict[str, Any]: Root folder contents and metadata
Example:
root πΎsdk.folder.list_root()
contents πΎroot['contents']
for item in contents:
if item.get('isfolder'):
print(f"Γ°ΒΒΒ {item['name']}/")
else:
print(f"Γ°ΒΒΒ {item['name']} ({item['size']} bytes)")
get_content()¶
Get folder content.
get_content(
folder_id: Optional[int] πΎNone,
path: Optional[str] πΎNone
) -π List[Dict[str, Any]]
Parameters:
- folder_id (Optional[int]): Folder ID
- path (Optional[str]): Folder path
Returns:
- List[Dict[str, Any]]: List of folder contents
create()¶
Create new folder.
Parameters:
- name (str): Folder name
- parent (int): Parent folder ID (0 πΎroot)
Returns:
- Union[int, Dict[str, Any]]: Folder ID or response dict
Example:
folder_id πΎsdk.folder.create("My New Folder", parent=0)
print(f"Created folder with ID: {folder_id}")
rename()¶
Rename folder.
Parameters:
- folder_id (int): Folder ID
- name (str): New name
Returns:
- Union[int, Dict[str, Any]]: Folder ID or response dict
move()¶
Move folder to another parent.
Parameters:
- folder_id (int): Folder ID to move
- new_parent (int): New parent folder ID
Returns:
- Union[int, Dict[str, Any]]: Folder ID or response dict
delete()¶
Delete folder.
Parameters:
- folder_id (int): Folder ID
Returns:
- Dict[str, Any]: Deletion result
delete_recursive()¶
Delete folder recursively.
Parameters:
- folder_id (int): Folder ID
Returns:
- Dict[str, Any]: Deletion result
File Operations¶
Access via sdk.file property.
upload()¶
Upload file to pCloud.
upload(
file_path: str,
folder_id: int πΎ0,
filename: Optional[str] πΎNone,
progress_callback: Optional[callable] πΎNone
) -π Dict[str, Any]
Parameters:
- file_path (str): Local file path
- folder_id (int): Destination folder ID (0 πΎroot)
- filename (Optional[str]): Custom filename (optional)
- progress_callback (Optional[callable]): Progress callback function
Returns:
- Dict[str, Any]: Upload result with file metadata
Example:
def progress(bytes_transferred, total_bytes, percentage, speed, **kwargs):
print(f"Upload: {percentage:.1f}% ({speed/1024/1024:.1f} MB/s)")
result πΎsdk.file.upload(
"/path/to/file.txt",
folder_id=0,
progress_callback=progress
)
file_id πΎresult['metadata'][0]['fileid']
download()¶
Download file from pCloud.
download(
file_id: int,
destination: str πΎ"",
progress_callback: Optional[callable] πΎNone
) -π bool
Parameters:
- file_id (int): File ID
- destination (str): Download destination directory
- progress_callback (Optional[callable]): Progress callback function
Returns:
- bool: True if successful
Example:
success πΎsdk.file.download(
file_id=123456,
destination="./downloads/",
progress_callback=progress
)
get_link()¶
Get download link for file.
Parameters:
- file_id (int): File ID
Returns:
- str: Download URL
get_info()¶
Get file information.
Parameters:
- file_id (int): File ID
Returns:
- Dict[str, Any]: File information including checksum
rename()¶
Rename file.
Parameters:
- file_id (int): File ID
- name (str): New filename
Returns:
- Dict[str, Any]: Operation result
move()¶
Move file to another folder.
Parameters:
- file_id (int): File ID
- folder_id (int): Destination folder ID
Returns:
- Dict[str, Any]: Operation result
copy()¶
Copy file to another folder.
Parameters:
- file_id (int): File ID
- folder_id (int): Destination folder ID
Returns:
- Dict[str, Any]: Operation result
delete()¶
Delete file.
Parameters:
- file_id (int): File ID
Returns:
- Dict[str, Any]: Deletion result
Progress Utilities¶
Built-in progress tracking utilities for upload and download operations.
Factory Functions¶
create_progress_bar()¶
Create a simple progress bar.
create_progress_bar(
title: str πΎ"Transfer",
width: int πΎ50,
show_speed: bool πΎTrue,
show_eta: bool πΎTrue
) -π SimpleProgressBar
Parameters:
- title (str): Progress bar title
- width (int): Progress bar width in characters
- show_speed (bool): Show transfer speed
- show_eta (bool): Show estimated time remaining
create_detailed_progress()¶
Create detailed progress tracker with logging.
Parameters:
- log_file (Optional[str]): Optional log file path
create_minimal_progress()¶
Create minimal progress tracker (milestones only).
create_silent_progress()¶
Create silent progress tracker (CSV logging only).
Parameters:
- log_file (str): CSV log file path
Progress Callback Interface¶
All progress callbacks receive these parameters:
def progress_callback(
bytes_transferred: int,
total_bytes: int,
percentage: float,
speed: float,
**kwargs
):
"""
Args:
bytes_transferred: Bytes transferred so far
total_bytes: Total bytes to transfer
percentage: Transfer percentage (0-100)
speed: Transfer speed in bytes per second
**kwargs: Additional information:
- operation: "upload" or "download"
- filename: File name
- status: "starting", "progress", "saving", "completed", "error"
- error: Error message (if status="error")
"""
pass
Core Classes¶
Advanced users can use core classes directly.
App Class¶
Main application configuration class.
from pcloud_sdk import App
app πΎApp()
app.set_app_key("client_id")
app.set_app_secret("client_secret")
app.set_access_token("token")
app.set_location_id(2)
Methods:¶
set_app_key(app_key: str)set_app_secret(app_secret: str)set_access_token(access_token: str, auth_type: str πΎ"oauth2")set_location_id(location_id: Union[str, int])get_authorize_code_url() -π strget_token_from_code(code: str, location_id: Union[str, int]) -π Dict[str, Any]login_with_credentials(email: str, password: str, location_id: Union[str, int] πΎ1) -π Dict[str, Any]
Request Class¶
HTTP request handler.
Response Class¶
HTTP response wrapper.
Configuration¶
Server Locations¶
# EU servers (default)
sdk πΎPCloudSDK(location_id=2)
# US servers
sdk πΎPCloudSDK(location_id=1)
Timeouts¶
File Upload Chunk Size¶
from pcloud_sdk.config import Config
# Default is 10MB chunks
Config.FILE_PART_SIZE πΎ5 * 1024 * 1024 # 5MB chunks
Exception Handling¶
PCloudException¶
Main exception class for pCloud SDK errors.
from pcloud_sdk import PCloudException
try:
result πΎsdk.file.upload("nonexistent.txt")
except PCloudException as e:
print(f"pCloud error: {e}")
print(f"Error code: {e.code}")
except Exception as e:
print(f"General error: {e}")
Attributes:
- message (str): Error message
- code (int): Error code (default: 5000)
Common Error Codes¶
1000: Authentication failed2000: File not found2001: Folder not found2003: Access denied2005: Folder already exists2008: File name too long2009: File or folder name is invalid5000: General error (default)
Error Handling Best Practices¶
import logging
from pcloud_sdk import PCloudSDK, PCloudException
# Set up logging
logging.basicConfig(level=logging.INFO)
logger πΎlogging.getLogger(__name__)
def safe_upload(file_path: str) -π bool:
"""Upload with comprehensive error handling"""
try:
sdk πΎPCloudSDK()
sdk.login() # May raise authentication error
result πΎsdk.file.upload(file_path)
logger.info(f"Upload successful: {file_path}")
return True
except PCloudException as e:
if e.code =πΎ1000:
logger.error("Authentication failed - check credentials")
elif e.code =πΎ2000:
logger.error(f"File not found: {file_path}")
else:
logger.error(f"pCloud error {e.code}: {e}")
return False
except FileNotFoundError:
logger.error(f"Local file not found: {file_path}")
return False
except Exception as e:
logger.error(f"Unexpected error: {e}")
return False
Rate Limiting¶
The pCloud API has rate limits. The SDK includes automatic retry logic for rate-limited requests:
# Automatic retry with exponential backoff
# No additional configuration needed
result πΎsdk.file.upload("large_file.zip")
Thread Safety¶
The SDK is not thread-safe. For concurrent operations, create separate SDK instances:
import threading
from pcloud_sdk import PCloudSDK
def worker_thread(file_path: str):
# Create separate SDK instance per thread
sdk πΎPCloudSDK()
sdk.login("user@example.com", "password")
sdk.file.upload(file_path)
# Start multiple threads
threads πΎ[]
for file_path in file_list:
thread πΎthreading.Thread(target=worker_thread, args=(file_path,))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
This completes the API reference. For more examples, see the Examples Guide.