Core API¶
Initialization¶
You can use pyuploadcare in any Python project. You need to pass
your project keys to Uploadcare client:
from pyuploadcare import Uploadcare
uploadcare = Uploadcare(
public_key='<your public key>',
secret_key='<your private key>'
)
By default file URLs use https://ucarecdn.com/. To use your project’s
CDN subdomain (https://<prefix>.ucarecd.net/) instead, set
UPLOADCARE_USE_SUBDOMAINS=yes in the environment, or pass cdn_base
explicitly. Subdomains will become the default in the next major release.
Uploading files¶
Upload single file. File.upload method can accept file object or URL. Depending of file object size
direct or multipart upload method will be chosen:
with open('file.txt', 'rb') as file_object:
ucare_file: File = uploadcare.upload(file_object)
Upload file from url:
ucare_file: File = uploadcare.upload("https://github.githubassets.com/images/modules/logos_page/Octocat.png")
Use upload_from_url or upload_from_url_sync to access additional parameters, such as check_duplicates and save_duplicates, when uploading from url:
file_from_url: FileFromUrl = uploadcare.upload_from_url(
"https://github.githubassets.com/images/modules/logos_page/Octocat.png",
store=True,
filename="octocat.png",
check_duplicates=True,
save_duplicates=True,
)
ucare_file: File = uploadcare.upload_from_url_sync(
"https://github.githubassets.com/images/modules/logos_page/Octocat.png",
)
Upload multiple files. Direct upload method is used:
file1 = open('file1.txt', 'rb')
file2 = open('file2.txt', 'rb')
ucare_files: List[File] = uploadcare.upload_files([file1, file2])
Send single file via multipart upload:
with open('file.txt', 'rb') as file_object:
ucare_file: File = uploadcare.upload(file_object)
Uploadcare.upload method accepts optional callback function to track uploading progress.
Example of using callback function for printing progress:
>>> def print_progress(info: UploadProgress):
... print(f'{info.done}/{info.total} B')
>>> # multipart upload is used
>>> with open('big_file.jpg', 'rb') as fh:
... uploadcare.upload(fh, callback=print_progress)
0/11000000 B
5242880/11000000 B
10485760/11000000 B
11000000/11000000 B
>>> # upload from url is used
>>> uploadcare.upload("https://github.githubassets.com/images/modules/logos_page/Octocat.png", callback=print_progress)
32590/32590 B
>>> # direct upload is used. Callback is called just once after successful upload
>>> with open('small_file.jpg', 'rb') as fh:
... uploadcare.upload(fh, callback=print_progress)
56780/56780 B
Manage files and file groups¶
Get a list of files:
files: FileList = uploadcare.list_files(stored=True, limit=10)
for file in files:
print(file.info)
Get an existing file:
file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
print(file.info)
Store a single file:
file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
file.store()
Store multiple files:
files = [
'6c5e9526-b0fe-4739-8975-72e8d5ee6342',
'a771f854-c2cb-408a-8c36-71af77811f3b'
]
uploadcare.store_files(files)
Delete a single file:
file: File = uploadcare.file("740e1b8c-1ad8-4324-b7ec-112c79d8eac2")
file.delete()
Delete multiple files:
files = [
'6c5e9526-b0fe-4739-8975-72e8d5ee6342',
'a771f854-c2cb-408a-8c36-71af77811f3b'
]
uploadcare.delete_files(files)
Create a file group:
file_1: File = uploadcare.file('6c5e9526-b0fe-4739-8975-72e8d5ee6342')
file_2: File = uploadcare.file('a771f854-c2cb-408a-8c36-71af77811f3b')
file_group: FileGroup = uploadcare.create_file_group([file_1, file_2])
Get a file group:
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
print(file_group.info)
Stores all group’s files:
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
file_group.store()
List file groups:
file_groups: List[FileGroup] = uploadcare.list_file_groups(limit=10)
for file_group in file_groups:
print(file_group.info)
Delete file groups:
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
file_group.delete()
To delete a file group and all the files it contains:
file_group: FileGroup = uploadcare.file_group('0513dda0-582f-447d-846f-096e5df9e2bb~2')
file_group.delete(delete_files=True)
Get project info:
project_info: ProjectInfo = uploadcare.get_project_info()
Arbitrary file metadata¶
You can store some additional information for a file (metadata documentation). Access is organized in key-value manner. Metadata may be initially set while uploading:
custom_metadata = {
"specific_key_1": "some_value_1",
"specific_key_2": "constant_for_this_planet",
}
with open('file.txt', 'rb') as file_object:
ucare_file: File = uploadcare.upload(file_object, metadata=custom_metadata)
While uploading multiple files at once you can set common metadata that will be applied for every file in collection:
file1 = open('file1.txt', 'rb')
file2 = open('file2.txt', 'rb')
ucare_files: List[File] = uploadcare.upload_files(
[file1, file2],
common_metadata=custom_metadata,
)
# don't forget to close the files, of course
Value may be set by key:
md_key, md_value = "new_key_for_filemeta", "obvious_value"
uploadcare.metadata_api.update_or_create_key(file_id, md_key, md_value)
Value may be deleted by key:
uploadcare.metadata_api.delete_key(file_id, mkey=md_key)
Value may be retrieved by key:
meta_value = uploadcare.metadata_api.get_key(file_id, mkey=md_key)
Or the whole metadata may be got at once:
file_metadata = uploadcare.metadata_api.get_all_metadata(file_id)
But you should better use a special attribute of File.info:
file_metadata = file.info["metadata"]
Searching files¶
A single search request (file search documentation) can combine full-text search, exact
matching, range filters and tag filters. At least one condition is required: query,
phrase, exact, datetime_uploaded, size, is_image or tags. fuzziness
and sort are modifiers and do not count as conditions:
from datetime import datetime, timezone
from pyuploadcare import (
DatetimeRange,
FileSearchRequest,
SearchExact,
SearchPhrase,
SizeRange,
TagsFilter,
)
response = uploadcare.search_files(
FileSearchRequest(
query='sunset',
tags=TagsFilter(all_=['cat'], none_=['draft']),
size=SizeRange(gt=1024, lte=10 * 1024 * 1024),
is_image=True,
fuzziness=True,
sort=['-score', 'size'],
),
limit=50,
)
print(response.total, response.per_page, response.next)
for file_info in response.results:
print(file_info.original_filename, file_info.tags)
query searches across all searchable fields and must be at least 4 characters. phrase
performs an ordered full-text match on a specific field, and exact matches values exactly:
request = FileSearchRequest(
phrase=SearchPhrase(original_filename='holiday photo'),
exact=SearchExact(detected_mime_type=['image/jpeg', 'image/png']),
datetime_uploaded=DatetimeRange(
gte=datetime(2024, 1, 1, tzinfo=timezone.utc)
),
)
A field cannot appear in both phrase and exact in the same request.
Note
DatetimeRange accepts only timezone-aware datetimes; a naive datetime
or a plain date raises ValidationError. The same rule applies to
starting_point in list_files() and list_file_groups(), which
raise ValueError. Only the ucare CLI is lenient: a datetime given
on the command line without a UTC offset is treated as UTC.
exact can also match metadata values. In the SDK this is a nested mapping, which is
serialized into the metadata[<key>] keys the API expects:
SearchExact(metadata={'album': ['holiday'], 'color': ['red']})
A request can equally be a plain dict, using the same shape:
response = uploadcare.search_files({
'exact': {'metadata': {'album': ['holiday']}},
'tags': {'all': ['cat']},
})
sort accepts 1 to 4 keys out of score, datetime_uploaded, size and
original_filename, each optionally prefixed with - for descending order. Keys must be
unique and the same key must not be given in both directions.
Without sort, results are ordered by relevance. A filter-only request has no query or
phrase to rank by, so its order is undefined — always give such a request an explicit
sort.
Search indexing is asynchronous, so a file is not findable the instant it is uploaded — expect a delay on the order of seconds. Do not search for a file you have just uploaded without retrying.
search_files returns a single page. Its limit is the page size, 1 to 100, and the server
defaults to 20; offset + limit must not exceed 1000. Search cannot reach past the first 1000
results, so narrow the query instead of paging deeper.
To walk pages, use iterate_search_files. Its limit means something different: as elsewhere
in the SDK, limit is the total number of results to yield and request_limit is the number
retrieved per request. The iterator follows the server’s next URL from page to page and clamps
the first request to the 1000-result window:
for file_info in uploadcare.iterate_search_files(
{'tags': {'all': ['cat']}, 'sort': ['-datetime_uploaded']}, limit=200
):
print(file_info.uuid)
Warning
Paging through a filter-only request without sort is unreliable: the order is undefined
between requests, so files may be skipped or repeated. iterate_search_files emits a
UserWarning in that case.
Pass include_appdata=True to embed application data in every result:
response = uploadcare.search_files(request, include_appdata=True)
print(response.results[0].appdata)
Each result carries a highlight with the matched tokens wrapped in <em> tags. A field in it
is populated only when that field matched a full-text condition, so a filter-only search
highlights nothing — expect either no highlight at all or one whose every field is None:
highlight = response.results[0].highlight
if highlight:
print(highlight.original_filename) # ['<em>sunset</em>-cat.jpg']
print(highlight.metadata) # {'album': 'summer <em>sunset</em>'}
Warning
highlight values contain user-controlled content (filenames, metadata) plus markup added
by the server. They are not trusted HTML — escape them before rendering.
Search is available from the CLI as well. As in list_files, --limit is the total number
of results to show (default 100) and --request_limit is the page size, which you seldom need
to change. Because a descending sort key starts with a dash, pass
it with --sort= so it is not read as another option:
ucare search_files --query sunset --tags_any cat dog --is_image true \
--size_gt 1024 --sort=-score --limit 50
The CLI covers every condition except exact.metadata, whose bracketed keys do not map onto a
command line option; use the Python API for that.
Video conversion¶
Uploadcare can encode video files from all popular formats, adjust their quality, format and dimensions, cut out a video fragment, and generate thumbnails via REST API.
After each video file upload you obtain a file identifier in UUID format. Then you can use this file identifier to convert your video in multiple ways:
file = uploadcare.file('740e1b8c-1ad8-4324-b7ec-112c79d8eac2')
transformation = (
VideoTransformation()
.format(Format.mp4)
.size(width=640, height=480, resize_mode=ResizeMode.add_padding)
.quality(Quality.lighter)
.cut(start_time='2:30.535', length='2:20.0')
.thumbs(10)
)
converted_file: File = file.convert(transformation)
or you can use API directly to convert single or multiple files:
transformation = VideoTransformation().format(VideoFormat.webm).thumbs(2)
paths: List[str] = [
transformation.path("740e1b8c-1ad8-4324-b7ec-112c79d8eac2"),
]
response = uploadcare.video_convert_api.convert(paths)
video_convert_info = response.result[0]
converted_file = uploadcare.file(video_convert_info.uuid)
video_convert_status = uploadcare.video_convert_api.status(video_convert_info.token)
Document Conversion¶
Uploadcare allows converting documents to the following target formats: doc, docx, xls, xlsx, odt, ods, rtf, txt, pdf, jpg, png. Document Conversion works via our REST API.
After each document file upload you obtain a file identifier in UUID format. Then you can use this file identifier to convert your document to a new format:
file = uploadcare.file('0e1cac48-1296-417f-9e7f-9bf13e330dcf')
transformation = DocumentTransformation().format(DocumentFormat.pdf)
converted_file: File = file.convert(transformation)
or create an image of a particular page (if using image format):
file = uploadcare.file('5dddafa0-a742-4a51-ac40-ae491201ff97')
transformation = DocumentTransformation().format(DocumentFormat.png).page(1)
converted_file: File = file.convert(transformation)
or create a file group of converted pages of a multipage document:
file = uploadcare.file('0e1cac48-1296-417f-9e7f-9bf13e330dcf')
transformation = DocumentTransformation().format(DocumentFormat.jpg)
file.convert(transformation, save_in_group=True)
converted_group: FileGroup = file.get_converted_document_group(DocumentFormat.jpg)
or you can use API directly to convert single or multiple files:
transformation = DocumentTransformation().format(DocumentFormat.pdf)
paths: List[str] = [
transformation.path("0e1cac48-1296-417f-9e7f-9bf13e330dcf"),
]
response = uploadcare.document_convert_api.convert([path])
document_convert_info = response.result[0]
converted_file = uploadcare.file(document_convert_info.uuid)
document_convert_status = uploadcare.document_convert_api.status(document_convert_info.token)
Get document info: the detected source format, the formats it can be converted to,
and the file groups already produced by save_in_group conversions:
info = uploadcare.document_convert_api.retrieve('740e1b8c-1ad8-4324-b7ec-112c79d8eac2')
info.format.name # 'pdf'
[f.name for f in info.format.conversion_formats] # ['doc', 'docx', 'jpg', 'png', ...]
info.format.converted_groups # {'jpg': 'f56f1e80-...-690861252070~4'}
info.error # None, or an error message
converted_groups maps a target format to the UUID of the group holding the converted
pages. File.get_converted_document_group() is a shortcut that reads this mapping and
returns the group as a FileGroup.
File actions (addons)¶
To perform operation provided by addon you need to select the file and to set parameters of execution. Parameters are always specified by particular addon. For example, AWS Rekognition addon has no params to setup:
from pyuploadcare.api.addon_entities import AddonRemoveBGExecutionParams
remove_bg_params = AddonRemoveBGExecutionParams(
crop=True,
crop_margin="20px",
scale="15%"
)
from pyuploadcare.api.addon_entities import AddonClamAVExecutionParams
clamav_params = AddonClamAVExecutionParams(purge_infected=True)
To execute addon call an API execute method with the file and parameters:
target_file = uploadcare.file("59fccca5-3af7-462f-905b-ed7de83b9762")
# params - from previous step
remove_bg_result = uploadcare.addons_api.execute(
target_file.uuid,
AddonLabels.REMOVE_BG,
remove_bg_params,
)
aws_recognition_result = uploadcare.addons_api.execute(
target_file.uuid,
AddonLabels.AWS_LABEL_RECOGNITION,
)
aws_moderation_result = uploadcare.addons_api.execute(
target_file.uuid,
AddonLabels.AWS_MODERATION_LABELS,
)
clamav_result = uploadcare.addons_api.execute(
target_file.uuid,
AddonLabels.CLAM_AV,
clamav_params,
)
Each of these *_result objects contains not the result of operation itself, but request_id of invoked task, so we can check the state of execution. To check status of performed task use status method:
addon_task_status = uploadcare.addons_api.status(request_id, addon)
If addon execution produces new data for file (like an AWS recognition does), this data will be placed at appdata complex attribute of File.info (see addons documentation):
file.update_info(include_appdata=True)
print(file.info["appdata"]["aws_rekognition_detect_labels"])
Webhooks¶
Create a webhook:
webhook: Webhook = uploadcare.create_webhook("https://path/to/webhook")
Create a webhook with a signing secret:
webhook = uploadcare.create_webhook(
target_url="https://path/to/webhook",
signing_secret="7kMVZivndx0ErgvhRKAr",
)
List webhooks:
webhooks: List[Webhook] = list(uploadcare.list_webhooks(limit=10))
Update a webhook:
webhook: Webhook = uploadcare.update_webhook(webhook_id, is_active=False)
Update a webhook’s signing secret:
webhook: Webhook = uploadcare.update_webhook(webhook_id, signing_secret="7kMVZivndx0ErgvhRKAr")
Delete a webhook:
uploadcare.delete_webhook(webhook_id)
Secure delivery¶
You can use your own custom domain and CDN provider for deliver files with authenticated URLs (see original documentation).
Generate secure URL for file:
from pyuploadcare import Uploadcare
from pyuploadcare.secure_url import AkamaiSecureUrlBuilderWithAclToken
secure_url_bulder = AkamaiSecureUrlBuilderWithAclToken(
"<your cdn>",
"<your secret for token generation>"
)
uploadcare = Uploadcare(
public_key='<your public key>',
secret_key='<your private key>',
secure_url_builder=secure_url_bulder,
)
secure_url = uploadcare.generate_secure_url('52da3bfc-7cd8-4861-8b05-126fef7a6994')
Generate just the token:
token = uploadcare.get_secure_url_token('52da3bfc-7cd8-4861-8b05-126fef7a6994')
Generate secure URL for file with transformations:
secure_url = uploadcare.generate_secure_url(
'52da3bfc-7cd8-4861-8b05-126fef7a6994/-/resize/640x/other/transformations/'
)
Generate secure URL for file, with the same signature valid for its transformations:
secure_url = uploadcare.generate_secure_url(
'52da3bfc-7cd8-4861-8b05-126fef7a6994',
wildcard=True
)
Generate secure URL for file by its URL (please notice the usage of a different builder class):
from pyuploadcare import Uploadcare
from pyuploadcare.secure_url import AkamaiSecureUrlBuilderWithUrlToken
secure_url_bulder = AkamaiSecureUrlBuilderWithUrlToken(
"<your cdn>",
"<your secret for token generation>"
)
uploadcare = Uploadcare(
public_key='<your public key>',
secret_key='<your private key>',
secure_url_builder=secure_url_bulder,
)
secure_url = uploadcare.generate_secure_url(
'https://cdn.yourdomain.com/52da3bfc-7cd8-4861-8b05-126fef7a6994/'
)
Image processing¶
Uploadcare allows to apply image transformations to files. File.cdn_url attribute returns CDN url:
>>> file_ = File('a771f854-c2cb-408a-8c36-71af77811f3b')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/
You can set default effects by string:
>>> file_.set_effects('effect/flip/-/effect/mirror/')
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/effect/flip/-/effect/mirror/
or by image transformation builder:
>>> file_.set_effects(ImageTransformation().grayscale().flip())
>>> file_.cdn_url
https://ucarecdn.com/a771f854-c2cb-408a-8c36-71af77811f3b/-/grayscale/-/flip/
To check out the list of available transformations, please refer to the URL API reference and to ImageTransformation class source code.