🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more

files-com

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

files-com

Python bindings for the Files.com API

1.6.6
Maintainers
2

Files.com Python Client

The content included here should be enough to get started, but please visit our Developer Documentation Website for the complete documentation.

Introduction

The Files.com Python package is the best way to use Files.com from applications written in the Python language.

Files.com customers use our Python package for directly working with files and folders as well as performing management tasks such as adding/removing users, onboarding counterparties, retrieving information about automations and more.

Every function in the Files.com application is available via Python. Nothing is excluded.

This package is officially supported by Files.com for Python 3.8+. Prior versions of Python are considered end-of-life by the Python Software Foundation and Files.com only supports environments that are still supported by their vendor. With that said, we believe that this package works in Python 3.5-3.7 as well.

The Python package uses the Files.com RESTful APIs via the HTTPS protocol (port 443) to securely communicate and transfer files so no firewall changes should be required in order to allow connectivity to Files.com.

Installation

Use pip to install the latest version of the Files.com package.

pip3 install Files.com

Files.com automatically pushes a new release to PIP every time a commit is made to the master branch on GitHub, so there is no benefit in directly linking the package from GitHub.

Files.com is Committed to Python

Python is the most commonly used language for custom integrations to Files.com. Our Files.com Desktop v6 application (that we publish) is also written in Python, using this exact same package.

Explore the files-sdk-python code on GitHub.

Getting Support

The Files.com Support team provides official support for all of our official Files.com integration tools.

To initiate a support conversation, you can send an Authenticated Support Request or simply send an E-Mail to support@files.com.

Authentication

There are two ways to authenticate: API Key authentication and Session-based authentication.

Authenticate with an API Key

Authenticating with an API key is the recommended authentication method for most scenarios, and is the method used in the examples on this site.

To use an API Key, first generate an API key from the web interface or via the API or an SDK.

Note that when using a user-specific API key, if the user is an administrator, you will have full access to the entire API. If the user is not an administrator, you will only be able to access files that user can access, and no access will be granted to site administration functions in the API.

import files_sdk

files_sdk.set_api_key("YOUR_API_KEY")

## Alternatively, you can specify the API key on a per-request basis in the final parameter to any method or initializer.
try:
  files_sdk.user.list(params, {"api_key": "YOUR_API_KEY"})
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)

Don't forget to replace the placeholder, YOUR_API_KEY, with your actual API key.

Authenticate with a Session

You can also authenticate by creating a user session using the username and password of an active user. If the user is an administrator, the session will have full access to all capabilities of Files.com. Sessions created from regular user accounts will only be able to access files that user can access, and no access will be granted to site administration functions.

Sessions use the exact same session timeout settings as web interface sessions. When a session times out, simply create a new session and resume where you left off. This process is not automatically handled by our SDKs because we do not want to store password information in memory without your explicit consent.

Logging In

To create a session, the create method is called on the files_sdk object with the user's username and password.

This returns a session object that can be used to authenticate SDK method calls.

import files_sdk

try:
  session = files_sdk.session.create({ "username": "motor", "password": "vroom" })
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)

Using a Session

Once a session has been created, you can store the session globally, use the session per object, or use the session per request to authenticate SDK operations.

import files_sdk

## You may set the returned session to be used by default for subsequent requests.
files_sdk.set_session(session)

try:
  # Alternatively, you can specify the session ID on a per-object basis in the second parameter to a model constructor.
  user = files_sdk.user.User(params, {"session_id": session.id})

  # You may also specify the session ID on a per-request basis in the final parameter to static methods.
  files_sdk.user.find(id, params, {"session_id": session.id})
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)

Logging Out

User sessions can be ended calling the destroy method on the session object.

session.destroy()

Configuration

Global configuration is performed by setting attributes on the files_sdk object.

Configuration Options

Base URL

Setting the base URL for the API is required if your site is configured to disable global acceleration. This can also be set to use a mock server in development or CI.

import files_sdk

files_sdk.base_url = "https://SUBDOMAIN.files.com"

Log Level

This SDK utilizes the standard Python logging framework. It will respect the global log level and you can set the module specific log level and other logging settings by getting the logger object in the standard manner as shown below:

import logging

logging.getLogger("files_sdk")

Console Log Level

Enables printing of messages to stderr in addition to normal logging.

Allowed values are:

  • None
  • "info"
  • "debug"
import files_sdk

files_sdk.console_log_level = "info"

Open Timeout

Open timeout in seconds. The default value is 30.

import files_sdk

files_sdk.open_timeout = 60

Read Timeout

Read timeout in seconds. The default value is 60.

import files_sdk

files_sdk.read_timeout = 90

Initial Network Retry Delay

Initial retry delay in seconds. The default value is 0.5.

import files_sdk

files_sdk.initial_network_retry_delay = 1

Maximum Retry Delay

Maximum network retry delay in seconds. The default value is 2.

import files_sdk

files_sdk.max_network_retry_delay = 5

Maximum Network Retries

Maximum number of retries. The default value is 3.

import files_sdk

files_sdk.max_network_retries = 5

Source IP

Configure the local IP address from which to send requests.

import files_sdk

files_sdk.source_ip = '10.1.2.3'

Sort and Filter

Several of the Files.com API resources have list operations that return multiple instances of the resource. The List operations can be sorted and filtered.

Sorting

To sort the returned data, pass in the sort_by method argument.

Each resource supports a unique set of valid sort fields and can only be sorted by one field at a time.

The argument value is a Python dictionary that has a key of the resource field name sort on and a value of either "asc" or "desc" to specify the sort order.

Special note about the List Folder Endpoint

For historical reasons, and to maintain compatibility with a variety of other cloud-based MFT and EFSS services, Folders will always be listed before Files when listing a Folder. This applies regardless of the sorting parameters you provide. These will be used, after the initial sort application of Folders before Files.

import files_sdk

try:
  # users sorted by username
  users = files_sdk.user.list({
    "sort_by": { "username": "asc" }
  })
  for user in users.auto_paging_iter():
    # Operate on user
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)

Filtering

Filters apply selection criteria to the underlying query that returns the results. They can be applied individually or combined with other filters, and the resulting data can be sorted by a single field.

Each resource supports a unique set of valid filter fields, filter combinations, and combinations of filters and sort fields.

The passed in argument value is a Python dictionary that has a key of the resource field name to filter on and a passed in value to use in the filter comparison.

Filter Types

FilterTypeDescription
filterExactFind resources that have an exact field value match to a passed in value. (i.e., FIELD_VALUE = PASS_IN_VALUE).
filter_prefixPatternFind resources where the specified field is prefixed by the supplied value. This is applicable to values that are strings.
filter_gtRangeFind resources that have a field value that is greater than the passed in value. (i.e., FIELD_VALUE > PASS_IN_VALUE).
filter_gteqRangeFind resources that have a field value that is greater than or equal to the passed in value. (i.e., FIELD_VALUE >= PASS_IN_VALUE).
filter_ltRangeFind resources that have a field value that is less than the passed in value. (i.e., FIELD_VALUE < PASS_IN_VALUE).
filter_lteqRangeFind resources that have a field value that is less than or equal to the passed in value. (i.e., FIELD_VALUE <= PASS_IN_VALUE).
import files_sdk

try:
  # non admin users
  users = files_sdk.user.list({
    "filter": { "not_site_admin": true }
  })
  for user in users.auto_paging_iter():
    # Operate on user
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)
import files_sdk

try:
  # users who haven't logged in since 2024-01-01
  users = files_sdk.user.list({
    "filter_gteq": { "last_login_at": "2024-01-01" }
  })
  for user in users.auto_paging_iter():
    # Operate on user
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)
import files_sdk

try:
  # users whose usernames start with 'test'
  users = files_sdk.user.list({
    "filter_prefix": { "username": "test" }
  })
  for user in users.auto_paging_iter():
    # Operate on user
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)
import files_sdk

try:
  # users whose usernames start with 'test' and are not admins
  users = files_sdk.user.list({
    "filter_prefix": { "username": "test" },
    "filter": { "not_site_admin": "true" },
    "sort_by": { "username": "asc" }
  })
  for user in users.auto_paging_iter():
    # Operate on user
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)

Foreign Language Support

The Files.com Python SDK supports localized responses by using the files_sdk.set_language configuration method. When configured, this guides the API in selecting a preferred language for applicable response content.

Language support currently applies to select human-facing fields only, such as notification messages and error descriptions.

If the specified language is not supported or the value is omitted, the API defaults to English.

import files_sdk

files_sdk.set_language('es')

Errors

The Files.com Python SDK will return errors by raising exceptions. There are many exception classes defined in the Files SDK that correspond to specific errors.

The raised exceptions come from two categories:

  • SDK Exceptions - errors that originate within the SDK
  • API Exceptions - errors that occur due to the response from the Files.com API. These errors are grouped into common error types.

There are several types of exceptions within each category. Exception classes indicate different types of errors and are named in a fashion that describe the general premise of the originating error. More details can be found in the err object message.

Use standard Python exception handling to detect and deal with errors. It is generally recommended to handle specific errors first, then handle the general files_sdk.error.Error exception as a catch-all.

import files_sdk

try:
  session = files_sdk.session.create({ "username": "USERNAME", "password": "BADPASSWORD" })
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)

Error Types

SDK Errors

SDK errors are general errors that occur within the SDK code. Each exception class inherits from a standard Error base class.

files_sdk.error.APIConnectionError -> files_sdk.error.Error -> Exception
SDK Exception Classes
Error Class NameDescription
APIConnectionErrorThe Files.com API cannot be reached
AuthenticationErrorNot enough authentication information has been provided
InvalidParameterErrorA passed in parameter is invalid
MissingParameterErrorA method parameter is missing
NotImplementedErrorThe called method has not be implemented by the SDK

API Errors

API errors are errors returned by the Files.com API. Each exception class inherits from an error group base class. The error group base class indicates a particular type of error.

files_sdk.error.FolderAdminPermissionRequiredError -> files_sdk.error.NotAuthorizedError -> files_sdk.error.APIError -> files_sdk.error.Error -> Exception
API Exception Classes
Error Class NameError Group
AgentUpgradeRequiredErrorBadRequestError
AttachmentTooLargeErrorBadRequestError
CannotDownloadDirectoryErrorBadRequestError
CantMoveWithMultipleLocationsErrorBadRequestError
DatetimeParseErrorBadRequestError
DestinationSameErrorBadRequestError
DoesNotSupportSortingErrorBadRequestError
FolderMustNotBeAFileErrorBadRequestError
FoldersNotAllowedErrorBadRequestError
InvalidBodyErrorBadRequestError
InvalidCursorErrorBadRequestError
InvalidCursorTypeForSortErrorBadRequestError
InvalidEtagsErrorBadRequestError
InvalidFilterAliasCombinationErrorBadRequestError
InvalidFilterFieldErrorBadRequestError
InvalidFilterParamErrorBadRequestError
InvalidFilterParamFormatErrorBadRequestError
InvalidFilterParamValueErrorBadRequestError
InvalidInputEncodingErrorBadRequestError
InvalidInterfaceErrorBadRequestError
InvalidOauthProviderErrorBadRequestError
InvalidPathErrorBadRequestError
InvalidReturnToUrlErrorBadRequestError
InvalidSortFieldErrorBadRequestError
InvalidSortFilterCombinationErrorBadRequestError
InvalidUploadOffsetErrorBadRequestError
InvalidUploadPartGapErrorBadRequestError
InvalidUploadPartSizeErrorBadRequestError
MethodNotAllowedErrorBadRequestError
MultipleSortParamsNotAllowedErrorBadRequestError
NoValidInputParamsErrorBadRequestError
PartNumberTooLargeErrorBadRequestError
PathCannotHaveTrailingWhitespaceErrorBadRequestError
ReauthenticationNeededFieldsErrorBadRequestError
RequestParamsContainInvalidCharacterErrorBadRequestError
RequestParamsInvalidErrorBadRequestError
RequestParamsRequiredErrorBadRequestError
SearchAllOnChildPathErrorBadRequestError
UnrecognizedSortIndexErrorBadRequestError
UnsupportedCurrencyErrorBadRequestError
UnsupportedHttpResponseFormatErrorBadRequestError
UnsupportedMediaTypeErrorBadRequestError
UserIdInvalidErrorBadRequestError
UserIdOnUserEndpointErrorBadRequestError
UserRequiredErrorBadRequestError
AdditionalAuthenticationRequiredErrorNotAuthenticatedError
ApiKeySessionsNotSupportedErrorNotAuthenticatedError
AuthenticationRequiredErrorNotAuthenticatedError
BundleRegistrationCodeFailedErrorNotAuthenticatedError
FilesAgentTokenFailedErrorNotAuthenticatedError
InboxRegistrationCodeFailedErrorNotAuthenticatedError
InvalidCredentialsErrorNotAuthenticatedError
InvalidOauthErrorNotAuthenticatedError
InvalidOrExpiredCodeErrorNotAuthenticatedError
InvalidSessionErrorNotAuthenticatedError
InvalidUsernameOrPasswordErrorNotAuthenticatedError
LockedOutErrorNotAuthenticatedError
LockoutRegionMismatchErrorNotAuthenticatedError
OneTimePasswordIncorrectErrorNotAuthenticatedError
TwoFactorAuthenticationErrorErrorNotAuthenticatedError
TwoFactorAuthenticationSetupExpiredErrorNotAuthenticatedError
ApiKeyIsDisabledErrorNotAuthorizedError
ApiKeyIsPathRestrictedErrorNotAuthorizedError
ApiKeyOnlyForDesktopAppErrorNotAuthorizedError
ApiKeyOnlyForMobileAppErrorNotAuthorizedError
ApiKeyOnlyForOfficeIntegrationErrorNotAuthorizedError
BillingOrSiteAdminPermissionRequiredErrorNotAuthorizedError
BillingPermissionRequiredErrorNotAuthorizedError
BundleMaximumUsesReachedErrorNotAuthorizedError
BundlePermissionRequiredErrorNotAuthorizedError
CannotLoginWhileUsingKeyErrorNotAuthorizedError
CantActForOtherUserErrorNotAuthorizedError
ContactAdminForPasswordChangeHelpErrorNotAuthorizedError
FilesAgentFailedAuthorizationErrorNotAuthorizedError
FolderAdminOrBillingPermissionRequiredErrorNotAuthorizedError
FolderAdminPermissionRequiredErrorNotAuthorizedError
FullPermissionRequiredErrorNotAuthorizedError
HistoryPermissionRequiredErrorNotAuthorizedError
InsufficientPermissionForParamsErrorNotAuthorizedError
InsufficientPermissionForSiteErrorNotAuthorizedError
MustAuthenticateWithApiKeyErrorNotAuthorizedError
NeedAdminPermissionForInboxErrorNotAuthorizedError
NonAdminsMustQueryByFolderOrPathErrorNotAuthorizedError
NotAllowedToCreateBundleErrorNotAuthorizedError
PasswordChangeNotRequiredErrorNotAuthorizedError
PasswordChangeRequiredErrorNotAuthorizedError
ReadOnlySessionErrorNotAuthorizedError
ReadPermissionRequiredErrorNotAuthorizedError
ReauthenticationFailedErrorNotAuthorizedError
ReauthenticationFailedFinalErrorNotAuthorizedError
ReauthenticationNeededActionErrorNotAuthorizedError
RecaptchaFailedErrorNotAuthorizedError
SelfManagedRequiredErrorNotAuthorizedError
SiteAdminRequiredErrorNotAuthorizedError
SiteFilesAreImmutableErrorNotAuthorizedError
TwoFactorAuthenticationRequiredErrorNotAuthorizedError
UserIdWithoutSiteAdminErrorNotAuthorizedError
WriteAndBundlePermissionRequiredErrorNotAuthorizedError
WritePermissionRequiredErrorNotAuthorizedError
ApiKeyNotFoundErrorNotFoundError
BundlePathNotFoundErrorNotFoundError
BundleRegistrationNotFoundErrorNotFoundError
CodeNotFoundErrorNotFoundError
FileNotFoundErrorNotFoundError
FileUploadNotFoundErrorNotFoundError
FolderNotFoundErrorNotFoundError
GroupNotFoundErrorNotFoundError
InboxNotFoundErrorNotFoundError
NestedNotFoundErrorNotFoundError
PlanNotFoundErrorNotFoundError
SiteNotFoundErrorNotFoundError
UserNotFoundErrorNotFoundError
AlreadyCompletedErrorProcessingFailureError
AutomationCannotBeRunManuallyErrorProcessingFailureError
BehaviorNotAllowedOnRemoteServerErrorProcessingFailureError
BundleOnlyAllowsPreviewsErrorProcessingFailureError
BundleOperationRequiresSubfolderErrorProcessingFailureError
CouldNotCreateParentErrorProcessingFailureError
DestinationExistsErrorProcessingFailureError
DestinationFolderLimitedErrorProcessingFailureError
DestinationParentConflictErrorProcessingFailureError
DestinationParentDoesNotExistErrorProcessingFailureError
ExceededRuntimeLimitErrorProcessingFailureError
ExpiredPrivateKeyErrorProcessingFailureError
ExpiredPublicKeyErrorProcessingFailureError
ExportFailureErrorProcessingFailureError
ExportNotReadyErrorProcessingFailureError
FailedToChangePasswordErrorProcessingFailureError
FileLockedErrorProcessingFailureError
FileNotUploadedErrorProcessingFailureError
FilePendingProcessingErrorProcessingFailureError
FileProcessingErrorErrorProcessingFailureError
FileTooBigToDecryptErrorProcessingFailureError
FileTooBigToEncryptErrorProcessingFailureError
FileUploadedToWrongRegionErrorProcessingFailureError
FilenameTooLongErrorProcessingFailureError
FolderLockedErrorProcessingFailureError
FolderNotEmptyErrorProcessingFailureError
HistoryUnavailableErrorProcessingFailureError
InvalidBundleCodeErrorProcessingFailureError
InvalidFileTypeErrorProcessingFailureError
InvalidFilenameErrorProcessingFailureError
InvalidPriorityColorErrorProcessingFailureError
InvalidRangeErrorProcessingFailureError
InvalidSiteErrorProcessingFailureError
ModelSaveErrorErrorProcessingFailureError
MultipleProcessingErrorsErrorProcessingFailureError
PathTooLongErrorProcessingFailureError
RecipientAlreadySharedErrorProcessingFailureError
RemoteServerErrorErrorProcessingFailureError
ResourceBelongsToParentSiteErrorProcessingFailureError
ResourceLockedErrorProcessingFailureError
SubfolderLockedErrorProcessingFailureError
TwoFactorAuthenticationCodeAlreadySentErrorProcessingFailureError
TwoFactorAuthenticationCountryBlacklistedErrorProcessingFailureError
TwoFactorAuthenticationGeneralErrorErrorProcessingFailureError
TwoFactorAuthenticationMethodUnsupportedErrorErrorProcessingFailureError
TwoFactorAuthenticationUnsubscribedRecipientErrorProcessingFailureError
UpdatesNotAllowedForRemotesErrorProcessingFailureError
DuplicateShareRecipientErrorRateLimitedError
ReauthenticationRateLimitedErrorRateLimitedError
TooManyConcurrentLoginsErrorRateLimitedError
TooManyConcurrentRequestsErrorRateLimitedError
TooManyLoginAttemptsErrorRateLimitedError
TooManyRequestsErrorRateLimitedError
TooManySharesErrorRateLimitedError
AgentUnavailableErrorServiceUnavailableError
AutomationsUnavailableErrorServiceUnavailableError
MigrationInProgressErrorServiceUnavailableError
SiteDisabledErrorServiceUnavailableError
UploadsUnavailableErrorServiceUnavailableError
AccountAlreadyExistsErrorSiteConfigurationError
AccountOverdueErrorSiteConfigurationError
NoAccountForSiteErrorSiteConfigurationError
SiteWasRemovedErrorSiteConfigurationError
TrialExpiredErrorSiteConfigurationError
TrialLockedErrorSiteConfigurationError
UserRequestsEnabledRequiredErrorSiteConfigurationError

Pagination

Certain API operations return lists of objects. When the number of objects in the list is large, the API will paginate the results.

The Files.com Python SDK provides multiple ways to paginate through lists of objects.

Automatic Pagination

The auto_paging_iter method automatically paginates and loads each page into memory.

import files_sdk

try:
  for item in files_sdk.folder.list_for("remote/path/to/folder").auto_paging_iter():
    print(item.type, item.path)
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)

Manual Pagination

The load_next_page/has_next_page methods allow for manual pagination and loading of each page into memory.

import files_sdk

try:
  list_obj = files_sdk.folder.list_for("remote/path/to/folder")

  while True:
    for item in list_obj:
      print(item.type, item.path)
    if not list_obj.has_next_page:
      break
    list_obj.load_next_page()
except files_sdk.error.NotAuthenticatedError as err:
  print(f"Authentication Error Occurred ({type(err).__name__}):", err)
except files_sdk.error.Error as err:
  print(f"Unknown Error Occurred ({type(err).__name__}):", err)

Case Sensitivity

The Files.com API compares files and paths in a case-insensitive manner. For related documentation see Case Sensitivity Documentation.

The path_util.is_same function in the Files.com SDK is designed to help you determine if two paths on your native file system would be considered the same on Files.com. This is particularly important when handling errors related to duplicate file names and when developing tools for folder synchronization.

import files_sdk

if files_sdk.path_util.is_same("Fïłèńämê.Txt", "filename.txt"):
    print("Paths are the same")

Mock Server

Files.com publishes a Files.com API server, which is useful for testing your use of the Files.com SDKs and other direct integrations against the Files.com API in an integration test environment.

It is a Ruby app that operates as a minimal server for the purpose of testing basic network operations and JSON encoding for your SDK or API client. It does not maintain state and it does not deeply inspect your submissions for correctness.

Eventually we will add more features intended for integration testing, such as the ability to intentionally provoke errors.

Download the server as a Docker image via Docker Hub.

The Source Code is also available on GitHub.

A README is available on the GitHub link.

FAQs

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts