Skip to content

Commit 11f68d8

Browse files
Add Collections API
Add `cloudinary.collections` to organize assets into collections and share them through public pages. - Collections: `collections`, `collection`, `create_collection`, `update_collection`, `delete_collection` - Assets: `collection_assets`, `add_collection_assets`, `remove_collection_assets` - Public pages: `collection_public_pages`, `collection_public_page`, `create_collection_public_page`, `update_collection_public_page`, `delete_collection_public_page` See `cloudinary/docs/organize-and-share-collections.md`. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 6ab5c2b commit 11f68d8

14 files changed

Lines changed: 982 additions & 6 deletions

‎AGENTS.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ offline or mocked tier. CI allocates a throwaway cloud per job via
4444
## Project structure
4545

4646
- `cloudinary/` — the package. `uploader.py` (Upload API), `api.py` (Admin API),
47-
`utils.py` (URL building, signing, transformation strings), `search.py`.
47+
`utils.py` (URL building, signing, transformation strings), `search.py`,
48+
`collections.py` (Collections API, imported explicitly like `api`).
4849
- `cloudinary/docs/` — version-matched Markdown task docs, shipped inside the
4950
published package. Keep in sync with the code they document.
5051
- `cloudinary/models.py`, `forms.py`, `templatetags/`, `templates/`, `static/` — the
@@ -67,6 +68,11 @@ offline or mocked tier. CI allocates a throwaway cloud per job via
6768
- Python 2/3 compatible source: the package still imports `six` and
6869
`cloudinary/compat.py`. Do not introduce f-strings, walrus operators, or
6970
type-annotation syntax into `cloudinary/`.
71+
- A module named after a standard-library module (e.g. `cloudinary/collections.py`)
72+
shadows it on Python 2. Every file in `cloudinary/` that imports that stdlib name
73+
needs `from __future__ import absolute_import`.
74+
- Every API error raises a `cloudinary.exceptions.Error` subclass. Map new HTTP
75+
statuses in `EXCEPTION_CODES` (`cloudinary/api_client/execute_request.py`).
7076
- 4-space indent, `snake_case`, module-level functions for API surface (not classes).
7177
- Public API convention: positional arguments first, then `**options` passed through
7278
to the API call.
@@ -83,6 +89,9 @@ offline or mocked tier. CI allocates a throwaway cloud per job via
8389
## Git workflow
8490

8591
- Branch from `master`; one topic per pull request.
92+
- Commit messages are public and user-facing: a short summary of the change and a
93+
pointer to the task doc. No usage examples, internal mechanics, or infrastructure
94+
detail; the docs are the reference.
8695
- Run `python -m pytest test` before opening a PR, and the Django suite when touching
8796
`models.py`, `forms.py`, or `templatetags/`.
8897
- Never rewrite published `CHANGELOG.md` entries; new entries go at the top and are
@@ -95,6 +104,11 @@ offline or mocked tier. CI allocates a throwaway cloud per job via
95104
**Always**
96105

97106
- Keep `cloudinary/docs/` and `examples/` consistent with the code they document.
107+
- A new API module needs a task doc in `cloudinary/docs/`, a runnable example in
108+
`examples/`, and links from `platform-capabilities.md`, `import-and-call.md`,
109+
`cloudinary/docs/README.md`, and `README.md`.
110+
- Document only behaviour verified against the live API. Do not document server-side
111+
bugs as expected behaviour.
98112
- Update tests when public behavior changes.
99113
- Keep API secrets out of examples, docs, tests, and fixtures.
100114

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ Save as `quickstart.py` and run `python quickstart.py`. [Create a free account](
7171
- [Transform and deliver an image](cloudinary/docs/transform-and-deliver-image.md)
7272
- [Transform and deliver a video](cloudinary/docs/transform-and-deliver-video.md)
7373
- [Search and manage assets](cloudinary/docs/search-and-manage-assets.md)
74+
- [Organize and share collections](cloudinary/docs/organize-and-share-collections.md)
7475
- [Moderate an upload](cloudinary/docs/moderate-upload.md)
7576
- [Use structured metadata](cloudinary/docs/use-structured-metadata.md)
7677
- [Use with Django](cloudinary/docs/use-with-django.md)

‎cloudinary/api_client/execute_request.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,14 @@
77

88
import cloudinary
99
from cloudinary.exceptions import (
10+
Error,
1011
BadRequest,
1112
AuthorizationRequired,
1213
NotAllowed,
1314
NotFound,
15+
NotAcceptable,
1416
AlreadyExists,
17+
Locked,
1518
RateLimited,
1619
GeneralError
1720
)
@@ -23,8 +26,10 @@
2326
401: AuthorizationRequired,
2427
403: NotAllowed,
2528
404: NotFound,
29+
406: NotAcceptable,
2630
409: AlreadyExists,
2731
420: RateLimited,
32+
423: Locked,
2833
429: RateLimited,
2934
500: GeneralError,
3035
503: GeneralError
@@ -88,8 +93,11 @@ def execute_request(http_connector, method, params, headers, auth, api_url, **op
8893
# Error is parsing json
8994
raise GeneralError("Error parsing server response (%d) - %s. Got - %s" % (response.status, body, e))
9095

96+
if response.status >= 400 and "error" not in result and "message" in result:
97+
result = {"error": {"message": result["message"]}}
98+
9199
if "error" in result:
92-
exception_class = EXCEPTION_CODES.get(response.status) or Exception
100+
exception_class = EXCEPTION_CODES.get(response.status) or Error
93101
raise exception_class("Error {0} - {1}".format(response.status, result["error"]["message"]))
94102

95103
return Response(result, response)

‎cloudinary/collections.py‎

Lines changed: 289 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,289 @@
1+
# Copyright Cloudinary
2+
3+
import json
4+
5+
from six import string_types
6+
7+
import cloudinary
8+
from cloudinary.api import only
9+
from cloudinary.api_client.call_api import _call_v2_api
10+
from cloudinary.utils import base64url_decode
11+
12+
CUSTOMER_ID_HEADER = "X-Cld-Customer-External-Id"
13+
14+
__COLLECTION_PARAMS = ["name", "description", "configuration"]
15+
16+
__PUBLIC_PAGE_PARAMS = ["name", "available_from", "expires_at", "show_download_original_option",
17+
"download_transformations", "create_download_transformations"]
18+
19+
__PUBLIC_PAGE_UPDATE_PARAMS = __PUBLIC_PAGE_PARAMS + ["protection_mode", "allowed_emails", "allowed_domains",
20+
"allow_any", "custom_layout_url"]
21+
22+
23+
def collections(**options):
24+
"""
25+
Lists the collections the caller may read, most-recently-updated first by default.
26+
27+
:param options: Additional options.
28+
:keyword str query: Case-insensitive filter on the collection name. Matches collections with a
29+
word in their name that starts with this text.
30+
:keyword str sort_by: Sort expression, "<field> <direction>", optionally comma-separated.
31+
Field is one of "name", "created_at" or "updated_at"; direction is "asc"
32+
or "desc". Defaults to "updated_at desc".
33+
:keyword int max_results: Maximum number of collections to return. 1-100, default 20.
34+
:keyword str next_cursor: The cursor from a previous response, to fetch the next page.
35+
:return: The collections, as {"data": [...], "next_cursor": ...}.
36+
:rtype: Response
37+
"""
38+
params = only(options, "query", "sort_by", "max_results", "next_cursor")
39+
return __call_collections_api("get", [], params, **options)
40+
41+
42+
def create_collection(name, **options):
43+
"""
44+
Creates a collection and makes the caller its owner.
45+
46+
:param name: The name of the collection.
47+
:type name: str
48+
:param options: Additional options.
49+
:keyword str description: The description of the collection.
50+
:keyword str type: "manual" (the default) holds an explicit asset list, populated with
51+
`add_collection_assets`; "dynamic" is populated by a saved search expression.
52+
:keyword dict configuration: The configuration of a dynamic collection, as
53+
{"expression": "<search expression>"}. Required for "dynamic",
54+
not allowed for "manual".
55+
:return: The created collection.
56+
:rtype: Response
57+
"""
58+
params = only(options, "description", "type", "configuration")
59+
params["name"] = name
60+
return __call_collections_api("post", [], params, **options)
61+
62+
63+
def collection(collection_id, **options):
64+
"""
65+
Returns a single collection.
66+
67+
:param collection_id: The external ID of the collection.
68+
:type collection_id: str
69+
:param options: Additional options.
70+
:return: The collection.
71+
:rtype: Response
72+
"""
73+
return __call_collections_api("get", [collection_id], {}, **options)
74+
75+
76+
def update_collection(collection_id, **options):
77+
"""
78+
Updates a collection. Only the fields passed are changed. The type of a collection can't be changed.
79+
80+
:param collection_id: The external ID of the collection.
81+
:type collection_id: str
82+
:param options: Additional options.
83+
:keyword str name: The new name of the collection.
84+
:keyword str description: The new description of the collection.
85+
:keyword dict configuration: The new configuration of a dynamic collection, as
86+
{"expression": "<search expression>"}.
87+
:return: The updated collection.
88+
:rtype: Response
89+
"""
90+
params = only(options, *__COLLECTION_PARAMS)
91+
return __call_collections_api("put", [collection_id], params, **options)
92+
93+
94+
def delete_collection(collection_id, **options):
95+
"""
96+
Deletes a collection. The assets in it are not modified or deleted.
97+
98+
:param collection_id: The external ID of the collection.
99+
:type collection_id: str
100+
:param options: Additional options.
101+
:return: A dictionary with a "message" key.
102+
:rtype: Response
103+
"""
104+
return __call_collections_api("delete", [collection_id], {}, **options)
105+
106+
107+
def collection_assets(collection_id, **options):
108+
"""
109+
Lists the assets in a collection that the caller may view, newest first by default.
110+
111+
:param collection_id: The external ID of the collection.
112+
:type collection_id: str
113+
:param options: Additional options.
114+
:keyword str sort_by: Sort expression, "<field> <direction>", optionally comma-separated.
115+
Field is one of "created_at", "uploaded_at", "public_id", "display_name"
116+
or "bytes"; direction is "asc" or "desc". Defaults to "created_at desc".
117+
Send the same sort_by on every page.
118+
:keyword int max_results: Maximum number of assets to return. 1-100, default 20.
119+
:keyword str next_cursor: The cursor from a previous response, to fetch the next page.
120+
:return: The assets, as {"data": [...], "next_cursor": ...}.
121+
:rtype: Response
122+
"""
123+
params = only(options, "sort_by", "max_results", "next_cursor")
124+
return __call_collections_api("get", [collection_id, "assets"], params, **options)
125+
126+
127+
def add_collection_assets(collection_id, asset_ids, **options):
128+
"""
129+
Adds assets to a collection.
130+
131+
:param collection_id: The external ID of the collection.
132+
:type collection_id: str
133+
:param asset_ids: The asset IDs of the assets to add. A single ID may be passed as a string.
134+
:type asset_ids: list[str] or str
135+
:param options: Additional options.
136+
:return: The collection.
137+
:rtype: Response
138+
"""
139+
return __call_collections_api("post", [collection_id, "assets"], __asset_ids_list(asset_ids), **options)
140+
141+
142+
def remove_collection_assets(collection_id, asset_ids, **options):
143+
"""
144+
Removes assets from a collection. Assets not in the collection are ignored, and the assets
145+
themselves are not modified or deleted.
146+
147+
:param collection_id: The external ID of the collection.
148+
:type collection_id: str
149+
:param asset_ids: The asset IDs of the assets to remove. A single ID may be passed as a string.
150+
:type asset_ids: list[str] or str
151+
:param options: Additional options.
152+
:return: The collection.
153+
:rtype: Response
154+
"""
155+
return __call_collections_api("delete", [collection_id, "assets"], __asset_ids_list(asset_ids), **options)
156+
157+
158+
def create_collection_public_page(collection_id, **options):
159+
"""
160+
Publishes a collection as a shareable public page.
161+
162+
:param collection_id: The external ID of the collection.
163+
:type collection_id: str
164+
:param options: Additional options.
165+
:keyword str name: The name of the public page.
166+
:keyword str available_from: The date-time (ISO 8601) the page becomes available.
167+
:keyword str expires_at: The date-time (ISO 8601) the page expires.
168+
:keyword bool show_download_original_option: Whether viewers can download the original assets.
169+
:keyword list download_transformations: Named transformations viewers can apply when downloading,
170+
as [{"name": "<name>", "types": ["image", ...]}, ...].
171+
At most 200.
172+
:keyword bool create_download_transformations: Whether to create any listed transformation name
173+
that isn't a transformation template yet.
174+
:return: The created public page, including its URL.
175+
:rtype: Response
176+
"""
177+
params = only(options, *__PUBLIC_PAGE_PARAMS)
178+
return __call_collections_api("post", [collection_id, "public_pages"], params, **options)
179+
180+
181+
def collection_public_pages(collection_id, **options):
182+
"""
183+
Lists the public pages of a collection.
184+
185+
:param collection_id: The external ID of the collection.
186+
:type collection_id: str
187+
:param options: Additional options.
188+
:return: The public pages, as {"data": [...]}.
189+
:rtype: Response
190+
"""
191+
return __call_collections_api("get", [collection_id, "public_pages"], {}, **options)
192+
193+
194+
def collection_public_page(collection_id, public_page_id, **options):
195+
"""
196+
Returns a single public page of a collection.
197+
198+
:param collection_id: The external ID of the collection.
199+
:type collection_id: str
200+
:param public_page_id: The external ID of the public page.
201+
:type public_page_id: str
202+
:param options: Additional options.
203+
:return: The public page.
204+
:rtype: Response
205+
"""
206+
return __call_collections_api("get", [collection_id, "public_pages", public_page_id], {}, **options)
207+
208+
209+
def update_collection_public_page(collection_id, public_page_id, **options):
210+
"""
211+
Updates the settings of a public page of a collection.
212+
213+
:param collection_id: The external ID of the collection.
214+
:type collection_id: str
215+
:param public_page_id: The external ID of the public page.
216+
:type public_page_id: str
217+
:param options: Additional options. Accepts the keywords of `create_collection_public_page`, and:
218+
:keyword str protection_mode: "none" or "email_otp". "email_otp" requires the secured-sharing
219+
feature on the plan.
220+
:keyword list allowed_emails: The emails allowed to open a protected page.
221+
:keyword list allowed_domains: The email domains allowed to open a protected page.
222+
:keyword bool allow_any: Whether any email may open a protected page.
223+
:keyword str custom_layout_url: The URL of a custom layout for the page.
224+
:return: The updated public page.
225+
:rtype: Response
226+
"""
227+
params = only(options, *__PUBLIC_PAGE_UPDATE_PARAMS)
228+
return __call_collections_api("put", [collection_id, "public_pages", public_page_id], params, **options)
229+
230+
231+
def delete_collection_public_page(collection_id, public_page_id, **options):
232+
"""
233+
Unpublishes a public page of a collection. The collection and its assets are not changed.
234+
235+
:param collection_id: The external ID of the collection.
236+
:type collection_id: str
237+
:param public_page_id: The external ID of the public page.
238+
:type public_page_id: str
239+
:param options: Additional options.
240+
:return: A dictionary with a "message" key.
241+
:rtype: Response
242+
"""
243+
return __call_collections_api("delete", [collection_id, "public_pages", public_page_id], {}, **options)
244+
245+
246+
def __asset_ids_list(asset_ids):
247+
"""
248+
Wraps a single asset ID in a list.
249+
250+
:internal
251+
"""
252+
return [asset_ids] if isinstance(asset_ids, string_types) else list(asset_ids)
253+
254+
255+
def __call_collections_api(method, uri, params, **options):
256+
"""
257+
Private function that assists with performing an API call to the collections endpoints.
258+
259+
:param method: The HTTP method. Valid methods: get, post, put, delete
260+
:param uri: REST endpoint of the API (without 'collections', the module or the cloud name)
261+
:param params: Query/body parameters passed to the method
262+
:param options: Additional options
263+
:rtype: Response
264+
:internal
265+
"""
266+
oauth_token = options.get("oauth_token", cloudinary.config().oauth_token)
267+
customer_id = __customer_external_id(oauth_token) if oauth_token else None
268+
if customer_id:
269+
extra_headers = {CUSTOMER_ID_HEADER: customer_id}
270+
extra_headers.update(options.get("extra_headers") or {})
271+
options["extra_headers"] = extra_headers
272+
273+
return _call_v2_api(method, ["collections"] + uri, params, module="asset_management", **options)
274+
275+
276+
def __customer_external_id(oauth_token):
277+
"""
278+
Reads ext.customer_external_id from an unverified JWT payload.
279+
280+
:param oauth_token: The OAuth access token.
281+
:return: The customer external ID, or None if absent or unreadable.
282+
:internal
283+
"""
284+
try:
285+
value = json.loads(base64url_decode(oauth_token.split(".")[1]))["ext"]["customer_external_id"]
286+
except (IndexError, KeyError, TypeError, ValueError):
287+
return None
288+
289+
return value if isinstance(value, string_types) and value else None

‎cloudinary/docs/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ directory of the repository.
4040
- [Transform and deliver an image](transform-and-deliver-image.md)
4141
- [Transform and deliver a video](transform-and-deliver-video.md)
4242
- [Search and manage assets](search-and-manage-assets.md)
43+
- [Organize and share collections](organize-and-share-collections.md)
4344
- [Moderate an upload](moderate-upload.md)
4445
- [Use structured metadata](use-structured-metadata.md)
4546
- [Use with Django](use-with-django.md)

‎cloudinary/docs/import-and-call.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ Import the submodules you use explicitly. `import cloudinary` on its own gives y
1414
`config()`, `CloudinaryImage`, `CloudinaryVideo`, `Search`, and `cloudinary.utils`,
1515
but **not** `cloudinary.uploader` or `cloudinary.api` — reaching for those raises
1616
`AttributeError: module 'cloudinary' has no attribute 'uploader'` until you import
17-
them.
17+
them. The same applies to `cloudinary.collections` — use
18+
`from cloudinary import collections`.
1819

1920
Calls are synchronous and return plain dictionaries. Positional arguments come first,
2021
then keyword options that pass through to the API:

0 commit comments

Comments
 (0)