### Install Wheel Package Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Install the imagekit-python library efficiently using the generated wheel file from the dist/ directory. ```sh pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Make Example Executable and Run Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md After adding a Python example script, make it executable using chmod and then run it from the project root. ```sh chmod +x examples/.py # run the example against your api $ ./examples/.py ``` -------------------------------- ### Install imagekitio with aiohttp support Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Install the ImageKit SDK with aiohttp support for improved concurrency performance in asynchronous operations. ```sh # install from PyPI pip install imagekitio[aiohttp] ``` -------------------------------- ### Add and Run Python Example Script Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Add new example scripts to the examples/ directory. Make them executable and then run them against your API. ```python # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` -------------------------------- ### Install ImageKit.io Python SDK Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Install the ImageKit.io Python SDK using pip. Ensure you are using Python 3.9+. ```sh pip install imagekitio ``` -------------------------------- ### Install Imagekit-Python from Git Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Install the imagekit-python library directly from its GitHub repository using pip. This is useful for testing unreleased changes. ```sh pip install git+ssh://git@github.com/imagekit-developer/imagekit-python#master.git ``` -------------------------------- ### Install Development Dependencies with Pip Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md If not using Rye, install development dependencies using pip by referencing the requirements-dev.lock file. Ensure your Python version matches the one specified in .python-version. ```sh pip install -r requirements-dev.lock ``` -------------------------------- ### Get Origin Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieve details for a specific origin server configuration using its ID. ```python client.accounts.origins.get(id) -> OriginResponse ``` -------------------------------- ### Determine Installed ImageKit Version Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Print the currently installed version of the imagekitio package. This is useful for debugging and ensuring compatibility. ```python import imagekitio print(imagekitio.__version__) ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md If Rye is installed manually, use this command to sync all dependencies, including features, for the project. ```sh rye sync --all-features ``` -------------------------------- ### URL Generation with Text Overlay Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Generate an ImageKit URL with a customized text overlay. This example is a placeholder and requires specific text and styling parameters to be defined. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), ) ``` -------------------------------- ### Async File Upload with aiohttp Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Upload a file asynchronously using the AsyncImageKit client with aiohttp as the HTTP backend. Ensure aiohttp is installed and imported. ```python import os import asyncio from imagekitio import DefaultAioHttpClient from imagekitio import AsyncImageKit async def main() -> None: async with AsyncImageKit( private_key=os.environ.get( "IMAGEKIT_PRIVATE_KEY" ), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: # Read file into memory and upload with open("/path/to/your/image.jpg", "rb") as f: file_data = f.read() response = await client.files.upload( file=file_data, file_name="file-name.jpg", ) print(response.file_id) print(response.url) asyncio.run(main()) ``` -------------------------------- ### Origins Get Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves the details of a specific origin configuration by its ID. ```APIDOC ## GET /v1/accounts/origins/{id} ### Description Retrieves the details of a specific origin configuration. ### Method GET ### Endpoint /v1/accounts/origins/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the origin to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the origin. - **name** (string) - The name of the origin. - **origin** (string) - The URL or identifier of the origin server. ``` -------------------------------- ### Get Authentication Parameters for Uploads (Python) Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Generates authentication parameters required for secure client-side file uploads. These include an expiration timestamp, signature, and token. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), ) # Generate authentication parameters for client-side uploads auth_params = client.helper.get_authentication_parameters() print(auth_params) ``` -------------------------------- ### Accounts Usage Get Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves the usage statistics for your ImageKit account, such as bandwidth, storage, and transformations. ```APIDOC ## GET /v1/accounts/usage ### Description Fetches the usage statistics for the ImageKit account. ### Method GET ### Endpoint /v1/accounts/usage ### Parameters #### Query Parameters - **startDate** (string) - Optional - The start date for the usage period (YYYY-MM-DD). - **endDate** (string) - Optional - The end date for the usage period (YYYY-MM-DD). ### Response #### Success Response (200) - **totalBandwidth** (integer) - Total bandwidth consumed in MB. - **totalStorage** (integer) - Total storage used in MB. - **totalTransformations** (integer) - Total number of transformations performed. ``` -------------------------------- ### Job Get Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves the status and details of a bulk job, such as folder copy, move, or rename operations. ```APIDOC ## GET /v1/bulkJobs/{jobId} ### Description Retrieves the status and details of a specific bulk job. ### Method GET ### Endpoint /v1/bulkJobs/{jobId} ### Parameters #### Path Parameters - **jobId** (string) - Required - The ID of the bulk job to retrieve. ### Response #### Success Response (200) - **jobId** (string) - The ID of the job. - **type** (string) - The type of the job (e.g., 'copyFolder', 'moveFolder'). - **status** (string) - The current status of the job (e.g., 'pending', 'processing', 'completed', 'failed'). - **createdAt** (string) - The timestamp when the job was created. ``` -------------------------------- ### Get URLEndpoint by ID Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Fetches a specific URL endpoint using its ID. Returns a URLEndpointResponse. ```python client.accounts.url_endpoints.get(id) -> URLEndpointResponse ``` -------------------------------- ### Get File Details Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves the details of a specific file using its file ID. This returns a File object with all its properties. ```python client.files.get(file_id) ``` -------------------------------- ### Get URL Endpoint Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves details for a specific URL endpoint using its ID. ```APIDOC ## GET /v1/accounts/url-endpoints/{id} ### Description Retrieves a specific URL endpoint. ### Method GET ### Endpoint /v1/accounts/url-endpoints/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the URL endpoint to retrieve. ### Response #### Success Response (200) - **URLEndpointResponse** (object) - Details of the requested URL endpoint. #### Response Example ```json { "example": "response body for specific URL endpoint" } ``` ``` -------------------------------- ### Get Account Usage Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieve account usage data. This method accepts parameters to filter the usage data. ```python from imagekitio.types.accounts import UsageGetResponse ``` ```python client.accounts.usage.get(**params) -> UsageGetResponse ``` -------------------------------- ### Invalidation Get Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves the status of a previously created cache invalidation request using its request ID. ```APIDOC ## GET /v1/files/purge/{requestId} ### Description Fetches the status and details of a specific cache invalidation job. ### Method GET ### Endpoint /v1/files/purge/{requestId} ### Parameters #### Path Parameters - **requestId** (string) - Required - The ID of the invalidation request to retrieve. ### Response #### Success Response (200) - **status** (string) - The current status of the invalidation request (e.g., 'processing', 'completed', 'failed'). - **filesPurged** (integer) - The number of files successfully purged. - **errors** (array) - A list of any errors encountered during the invalidation process. ``` -------------------------------- ### Get Cache Invalidation Status Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieve the status of a cache invalidation request using its unique ID. ```python client.cache.invalidation.get(request_id) -> InvalidationGetResponse ``` -------------------------------- ### Get Folder Job Status Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieve the status of a folder-related bulk job using its unique job ID. ```python from imagekitio.types.folders import JobGetResponse ``` ```python client.folders.job.get(job_id) -> JobGetResponse ``` -------------------------------- ### Make Undocumented POST Requests Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Use `client.post` for undocumented endpoints. Client options like retries are respected. Specify `cast_to=httpx.Response` to get the raw response object. ```python import httpx response = client.post( "/foo", cast_to=httpx.Response, body={"my_param": True}, ) print(response.headers.get("x-foo")) ``` -------------------------------- ### Initialize ImageKit Client and Upload File Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Initialize the ImageKit client with your private key (recommended to use environment variables) and upload a file. The response contains the file ID and URL. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted ) # Upload a file with open("/path/to/your/image.jpg", "rb") as f: file_data = f.read() response = client.files.upload( file=file_data, file_name="uploaded-image.jpg", ) print(response.file_id) print(response.url) ``` -------------------------------- ### Bootstrap Development Environment with Rye Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Run this script to set up the development environment using Rye, which automatically provisions the correct Python version and manages dependencies. ```sh ./scripts/bootstrap ``` -------------------------------- ### Enable Logging Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Enable logging by setting the IMAGE_KIT_LOG environment variable to 'info' for general logs or 'debug' for verbose output. ```shell $ export IMAGE_KIT_LOG=info ``` -------------------------------- ### Build Wheel Package Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Create distributable package files (.tar.gz and .whl) for the library. This command can be run using Rye or directly with the Python build module. ```sh rye build # or $ python -m build ``` -------------------------------- ### Run Tests Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Execute the project's test suite using the provided test script. ```sh ./scripts/test ``` -------------------------------- ### Download and Upload from URL Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Downloads content from a URL first and then uploads it to ImageKit. Direct URL uploads are not supported. ```python import urllib.request from imagekitio import ImageKit client = ImageKit() # Download from URL and upload to ImageKit url = "https://example.com/image.jpg" with urllib.request.urlopen(url) as response: url_content = response.read() # Upload the downloaded content upload_response = client.files.upload( file=url_content, file_name="downloaded-image.jpg", ) ``` -------------------------------- ### Create Folder Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Use this method to create a new folder. It accepts parameters for the folder's name and parent path. ```python from imagekitio.types import ( FolderCreateResponse, FolderDeleteResponse, FolderCopyResponse, FolderMoveResponse, FolderRenameResponse, ) ``` ```python client.folders.create(**params) -> FolderCreateResponse ``` -------------------------------- ### Upload File with Transformations Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Upload a file and apply transformations using nested parameters. Transformations can include resizing, cropping, and other image manipulations. ```python from imagekitio import ImageKit client = ImageKit() # Read file into memory and upload with open("/path/to/file.jpg", "rb") as f: file_data = f.read() response = client.files.upload( file=file_data, file_name="fileName", transformation={ "post": [ { "type": "thumbnail", "value": "w-150,h-150", }, { "protocol": "dash", "type": "abs", "value": "sr-240_360_480_720_1080", }, ] }, ) print(response.file_id) ``` -------------------------------- ### Generate URL with Text Overlay (Python) Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Builds a URL for an image with a text overlay. Specify text content, position, and transformations for the overlay. ```python url = client.helper.build_url( url_endpoint="https://ik.imagekit.io/your_imagekit_id", src="/path/to/base-image.jpg", transformation=[ { "width": 600, "height": 400, "overlay": { "type": "text", "text": "Sample Text Overlay", "position": { "x": 50, "y": 50, "focus": "center", }, "transformation": [ { "font_size": 40, "font_family": "Arial", "font_color": "FFFFFF", "typography": "b", # bold } ], }, } ], ) print(url) ``` -------------------------------- ### Create Origin Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Use this method to create a new origin server configuration. It requires parameters defining the origin details. ```python from imagekitio.types.accounts import OriginRequest, OriginResponse, OriginListResponse ``` ```python client.accounts.origins.create(**params) -> OriginResponse ``` -------------------------------- ### Configure ImageKit Client with Custom HTTP Client Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Initialize the ImageKit client with a custom httpx client, specifying proxy and transport options. This is useful for advanced network configurations. ```python import httpx from imagekitio import ImageKit, DefaultHttpxClient client = ImageKit( # Or use the `IMAGE_KIT_BASE_URL` env var base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Basic URL Generation Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Generate a simple ImageKit URL for a given source path without any transformations. Requires the ImageKit client to be initialized. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), ) # Basic URL without transformations url = client.helper.build_url( url_endpoint="https://ik.imagekit.io/your_imagekit_id", src="/path/to/image.jpg", ) print(url) # Result: https://ik.imagekit.io/your_imagekit_id/path/to/image.jpg ``` -------------------------------- ### Manage HTTP Resources with Context Manager Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Use the ImageKit client as a context manager to ensure underlying HTTP connections are properly closed upon exiting the block. This is the recommended way to manage resources. ```python from imagekitio import ImageKit with ImageKit() as client: # make requests here ... ``` -------------------------------- ### Upload File (Beta V2) Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Uploads a file using the beta V2 API. Requires file upload parameters. ```python client.beta.v2.files.upload(**params) -> FileUploadResponse ``` -------------------------------- ### Copy File Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Creates a copy of an existing file. This method requires parameters specifying the source file and destination details. ```python client.files.copy(**params) ``` -------------------------------- ### URL Generation with Image Overlay Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Generate an ImageKit URL with an image overlay applied to the base image. Specify the overlay image source and its position. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), ) # URL with image overlay url = client.helper.build_url( url_endpoint="https://ik.imagekit.io/your_imagekit_id", src="/path/to/base-image.jpg", transformation=[ { "width": 500, "height": 400, "overlay": { "type": "image", "input": "/path/to/overlay-logo.png", "position": { "x": 10, "y": 10, }, "transformation": [ { "width": 100, "height": 50, } ], }, } ], ) print(url) # Result: URL with image overlay positioned at x:10, y:10 ``` -------------------------------- ### Publish PyPI Manually Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Manually release a package to PyPI by executing the bin/publish-pypi script. Ensure the PYPI_TOKEN environment variable is set. ```sh bin/publish-pypi ``` -------------------------------- ### Generate URL with Multiple Overlays (Python) Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Combines multiple overlays, such as text and an image, onto a base image. Useful for complex compositions like watermarking. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), ) # URL with multiple overlays (text + image) url = client.helper.build_url( url_endpoint="https://ik.imagekit.io/your_imagekit_id", src="/path/to/base-image.jpg", transformation=[ { "width": 800, "height": 600, "overlay": { "type": "text", "text": "Header Text", "position": { "x": 20, "y": 20, }, "transformation": [ { "font_size": 30, "font_color": "000000", } ], }, }, { "overlay": { "type": "image", "input": "/watermark.png", "position": { "focus": "bottom_right", }, "transformation": [ { "width": 100, "opacity": 70, } ], }, }, ], ) print(url) ``` -------------------------------- ### Create URLEndpoint Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Creates a new URL endpoint using the ImageKit client. Requires URL endpoint creation parameters. ```python client.accounts.url_endpoints.create(**params) -> URLEndpointResponse ``` -------------------------------- ### List Origins Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieve a list of all configured origin servers for the account. ```python client.accounts.origins.list() -> OriginListResponse ``` -------------------------------- ### Folder Create Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Creates a new folder within your ImageKit media library. Folders help organize your files. ```APIDOC ## POST /v1/folder ### Description Creates a new folder in the ImageKit media library. ### Method POST ### Endpoint /v1/folder ### Parameters #### Request Body - **params** (object) - Required - Contains the name of the folder to be created. - **name** (string) - Required - The name of the new folder. - **parentFolder** (string) - Optional - The path of the parent folder where the new folder should be created. ### Response #### Success Response (200) - **name** (string) - The name of the created folder. - **path** (string) - The full path of the created folder. - **type** (string) - The type of the created entity (e.g., 'folder'). ``` -------------------------------- ### URL Generation with Transformations Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Generate an ImageKit URL with common transformations applied, such as resizing, cropping, and format conversion. Specify transformations in a list of dictionaries. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), ) # URL with basic transformations url = client.helper.build_url( url_endpoint="https://ik.imagekit.io/your_imagekit_id", src="/path/to/image.jpg", transformation=[ { "width": 400, "height": 300, "crop": "maintain_ratio", "quality": 80, "format": "webp", } ], ) print(url) # Result: https://ik.imagekit.io/your_imagekit_id/path/to/image.jpg?tr=w-400,h-300,c-maintain_ratio,q-80,f-webp ``` -------------------------------- ### Asset Listing Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md List all assets managed by ImageKit. ```APIDOC # Assets ### Description Provides functionality to list assets. ### Methods - **List Assets** - **Method**: GET - **Endpoint**: `/v1/files` - **Description**: Retrieves a list of all assets. - **Code Example**: `client.assets.list(**params)` ``` -------------------------------- ### Customize HTTP Client Per-Request Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Override the HTTP client for individual requests using the `with_options()` method. This allows for dynamic client configuration. ```python client.with_options(http_client=DefaultHttpxClient(...)) ``` -------------------------------- ### Upload File (v2 Beta) Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Uploads a file using the v2 beta API. This method supports various upload parameters. ```APIDOC ## POST /api/v2/files/upload ### Description Uploads a file using the v2 beta API. ### Method POST ### Endpoint /api/v2/files/upload ### Parameters #### Request Body - **params** (object) - Required - Parameters for uploading the file. ### Request Example ```json { "example": "request body for file upload" } ``` ### Response #### Success Response (200) - **FileUploadResponse** (object) - Details of the uploaded file. #### Response Example ```json { "example": "response body for uploaded file" } ``` ``` -------------------------------- ### Origins Create Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Creates a new origin configuration for your ImageKit account, specifying where your original files are stored. ```APIDOC ## POST /v1/accounts/origins ### Description Creates a new origin configuration for the ImageKit account. ### Method POST ### Endpoint /v1/accounts/origins ### Parameters #### Request Body - **params** (object) - Required - Contains the details of the origin to be created. - **name** (string) - Required - A unique name for the origin. - **origin** (string) - Required - The URL or identifier of the origin server. - **acl** (string) - Optional - Access control list settings for the origin. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created origin. - **name** (string) - The name of the origin. - **origin** (string) - The URL or identifier of the origin server. ``` -------------------------------- ### Configure Granular Timeout Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Use an httpx.Timeout object for more detailed control over connect, read, write, and overall request timeouts. ```python client = ImageKit( timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), ) ``` -------------------------------- ### Upload File using Path Object Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Uploads a file by providing a Path object. The SDK automatically reads the file contents. ```python from pathlib import Path from imagekitio import ImageKit client = ImageKit() # Method 3: Upload using Path object (SDK reads automatically) response = client.files.upload( file=Path("/path/to/file.jpg"), file_name="fileName.jpg", ) ``` -------------------------------- ### Async File Upload Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Upload a file asynchronously using the AsyncImageKit client. Requires the file to be read into memory. ```python import os import asyncio from imagekitio import AsyncImageKit client = AsyncImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), # This is the default and can be omitted ) async def main() -> None: # Read file into memory and upload with open("/path/to/your/image.jpg", "rb") as f: file_data = f.read() response = await client.files.upload( file=file_data, file_name="file-name.jpg", ) print(response.file_id) print(response.url) asyncio.run(main()) ``` -------------------------------- ### Origins List Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves a list of all configured origin servers for your ImageKit account. ```APIDOC ## GET /v1/accounts/origins ### Description Retrieves a list of all configured origin servers for the account. ### Method GET ### Endpoint /v1/accounts/origins ### Response #### Success Response (200) - **results** (array) - A list of origin objects. - **id** (string) - The ID of the origin. - **name** (string) - The name of the origin. - **origin** (string) - The URL or identifier of the origin server. ``` -------------------------------- ### Generate Expiring Signed URL (Python) Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Creates a signed URL for secure delivery that expires after a specified duration. Requires private key for signing. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), ) # Generate a signed URL that expires in 1 hour (3600 seconds) url = client.helper.build_url( url_endpoint="https://ik.imagekit.io/your_imagekit_id", src="/private/secure-image.jpg", transformation=[ { "width": 400, "height": 300, "quality": 90, } ], signed=True, expires_in=3600, # URL expires in 1 hour ) print(url) ``` -------------------------------- ### Configure Default Timeout Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Set the default timeout for all requests. The default is 1 minute. ```python from imagekitio import ImageKit # Configure the default for all requests: client = ImageKit( # 20 seconds (default is 1 minute) timeout=20.0, ) ``` -------------------------------- ### Lint Code Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Run the linting process using the configured ruff tool to check for code style and potential errors. ```sh ./scripts/lint ``` -------------------------------- ### Import URLEndpoint Types Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Imports necessary types for URLEndpoint requests, responses, and lists. ```python from imagekitio.types.accounts import ( URLEndpointRequest, URLEndpointResponse, URLEndpointListResponse, ) ``` -------------------------------- ### List URLEndpoints Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves a list of all URL endpoints. Returns a URLEndpointListResponse. ```python client.accounts.url_endpoints.list() -> URLEndpointListResponse ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Activate the project's virtual environment to run Python scripts without the 'rye run' prefix. This command is standard for Unix-like systems. ```sh source .venv/bin/activate ``` -------------------------------- ### Upload File from Bytes Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Uploads a file by reading its content into bytes in memory. Suitable for smaller files. ```python from imagekitio import ImageKit client = ImageKit() # Method 1: Upload from bytes # Read file into memory first, then upload with open("/path/to/your/image.jpg", "rb") as f: file_data = f.read() response = client.files.upload( file=file_data, file_name="uploaded-image.jpg", ) ``` -------------------------------- ### Import FileUploadResponse Type Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Imports the FileUploadResponse type for beta V2 file uploads. ```python from imagekitio.types.beta.v2 import FileUploadResponse ``` -------------------------------- ### Use Raw Transformations (Python) Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Applies raw transformations to an image URL, allowing the use of undocumented or custom transformation strings. Useful for accessing new features. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), ) # Using Raw transformation for undocumented or new parameters url = client.helper.build_url( url_endpoint="https://ik.imagekit.io/your_imagekit_id", src="/path/to/image.jpg", transformation=[ { # Combine documented transformations with raw parameters "width": 400, "height": 300, }, { # Use raw for undocumented transformations or complex parameters "raw": "something-new", }, ], ) print(url) ``` -------------------------------- ### Publish PyPI with GitHub Workflow Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Release packages to PyPI by utilizing the 'Publish PyPI' GitHub action. This requires specific organization or repository secrets to be configured. ```sh https://www.github.com/imagekit-developer/imagekit-python/actions/workflows/publish-pypi.yml ``` -------------------------------- ### Upload File from BytesIO Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Uploads programmatically generated binary content using a BytesIO object. ```python import io from imagekitio import ImageKit client = ImageKit() # Method 4: Upload from BytesIO (for programmatically generated content) content = b"your binary data" bytes_io = io.BytesIO(content) response = client.files.upload( file=bytes_io, file_name="binary-upload.jpg", ) ``` -------------------------------- ### Format Code with Ruff Source: https://github.com/imagekit-developer/imagekit-python/blob/master/CONTRIBUTING.md Automatically format the code and fix ruff issues to adhere to the project's coding standards. ```sh ./scripts/format ``` -------------------------------- ### Import Webhook Event Types Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Imports various webhook event types for handling ImageKit events. ```python from imagekitio.types import ( BaseWebhookEvent, FileCreateEvent, FileDeleteEvent, FileUpdateEvent, FileVersionCreateEvent, FileVersionDeleteEvent, UploadPostTransformErrorEvent, UploadPostTransformSuccessEvent, UploadPreTransformErrorEvent, UploadPreTransformSuccessEvent, VideoTransformationAcceptedEvent, VideoTransformationErrorEvent, VideoTransformationReadyEvent, UnsafeUnwrapWebhookEvent, UnwrapWebhookEvent, ) ``` -------------------------------- ### File Version Management Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Manage versions of files, including listing, deleting, retrieving, and restoring. ```APIDOC ## File Versions ### Description Manages different versions of files. ### Methods - **List File Versions** - **Method**: GET - **Endpoint**: `/v1/files/{fileId}/versions` - **Description**: Retrieves a list of all versions for a given file. - **Parameters**: - `file_id` (string) - Required - The ID of the file. - **Code Example**: `client.files.versions.list(file_id)` - **Delete File Version** - **Method**: DELETE - **Endpoint**: `/v1/files/{fileId}/versions/{versionId}` - **Description**: Deletes a specific version of a file. - **Parameters**: - `version_id` (string) - Required - The ID of the version to delete. - `file_id` (string) - Required - The ID of the file. - **Code Example**: `client.files.versions.delete(version_id, file_id=file_id)` - **Get File Version** - **Method**: GET - **Endpoint**: `/v1/files/{fileId}/versions/{versionId}` - **Description**: Retrieves details of a specific file version. - **Parameters**: - `version_id` (string) - Required - The ID of the version. - `file_id` (string) - Required - The ID of the file. - **Code Example**: `client.files.versions.get(version_id, file_id=file_id)` - **Restore File Version** - **Method**: PUT - **Endpoint**: `/v1/files/{fileId}/versions/{versionId}/restore` - **Description**: Restores a previously deleted file version. - **Parameters**: - `version_id` (string) - Required - The ID of the version to restore. - `file_id` (string) - Required - The ID of the file. - **Code Example**: `client.files.versions.restore(version_id, file_id=file_id)` ``` -------------------------------- ### Generate Custom Authentication Parameters Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Generates authentication parameters with a custom token and expiry time. These are useful for client-side uploads. ```python custom_auth_params = client.helper.get_authentication_parameters( token="my-custom-token", expire=1800 ) print(custom_auth_params) ``` -------------------------------- ### Upload File from File Stream Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Uploads a file by passing a file object directly, which is efficient for large files as the SDK reads it incrementally. ```python from imagekitio import ImageKit client = ImageKit() # Method 2: Upload from file stream (for large files) # Pass file object directly - SDK reads it with open("/path/to/your/image.jpg", "rb") as file_stream: response = client.files.upload( file=file_stream, file_name="uploaded-image.jpg", ) ``` -------------------------------- ### Configure Per-Request Timeout Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Override the default timeout settings for a specific request. ```python with open("/path/to/your/image.jpg", "rb") as f: file_data = f.read() client.with_options(timeout=5.0).files.upload( file=file_data, file_name="file-name.jpg", ) ``` -------------------------------- ### Copy Folder Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Use this method to copy a folder and its contents to a new location. It requires parameters for the source and destination paths. ```python client.folders.copy(**params) -> FolderCopyResponse ``` -------------------------------- ### Upload File with Custom Content Type Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Uploads a file using a tuple format to specify the filename, content, and custom media type. ```python from imagekitio import ImageKit client = ImageKit() # Method 5: Upload with custom content type using tuple format image_data = b"your binary data" response = client.files.upload( file=("custom.jpg", image_data, "image/jpeg"), file_name="custom-upload.jpg", ) ``` -------------------------------- ### Origins Update Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Updates an existing origin configuration for your ImageKit account. ```APIDOC ## PUT /v1/accounts/origins/{id} ### Description Updates an existing origin configuration. ### Method PUT ### Endpoint /v1/accounts/origins/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the origin to update. #### Request Body - **params** (object) - Required - Contains the updated details of the origin. - **name** (string) - Optional - The new name for the origin. - **origin** (string) - Optional - The new URL or identifier of the origin server. - **acl** (string) - Optional - Updated access control list settings for the origin. ### Response #### Success Response (200) - **id** (string) - The ID of the updated origin. - **name** (string) - The name of the origin. - **origin** (string) - The URL or identifier of the origin server. ``` -------------------------------- ### Handle API Errors Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Demonstrates how to catch and handle various ImageKit API errors, including connection issues and non-success status codes. ```python import imagekitio from imagekitio import ImageKit client = ImageKit() try: # Read file into memory and upload with open("/path/to/your/image.jpg", "rb") as f: file_data = f.read() response = client.files.upload( file=file_data, file_name="file-name.jpg", ) except imagekitio.APIConnectionError as e: print("The server could not be reached") print(e.__cause__) # an underlying Exception, likely raised within httpx. except imagekitio.RateLimitError as e: print("A 429 status code was received; we should back off a bit.") except imagekitio.APIStatusError as e: print("Another non-200-range status code was received") print(e.status_code) print(e.response) ``` -------------------------------- ### List URL Endpoints Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves a list of all configured URL endpoints for the account. Useful for auditing or managing existing endpoints. ```APIDOC ## GET /v1/accounts/url-endpoints ### Description Retrieves a list of all URL endpoints. ### Method GET ### Endpoint /v1/accounts/url-endpoints ### Response #### Success Response (200) - **URLEndpointListResponse** (object) - A list of URL endpoint objects. #### Response Example ```json { "example": "response body for list of URL endpoints" } ``` ``` -------------------------------- ### Move Folder Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Use this method to move a folder and its contents to a new location. It requires parameters for the source and destination paths. ```python client.folders.move(**params) -> FolderMoveResponse ``` -------------------------------- ### Access Raw Response with Headers Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Prefix HTTP method calls with `.with_raw_response.` to access the raw `APIResponse` object, including headers. The response content must be explicitly parsed. ```python from imagekitio import ImageKit client = ImageKit() # Read file into memory and upload with open("/path/to/your/image.jpg", "rb") as f: file_data = f.read() response = client.files.with_raw_response.upload( file=file_data, file_name="file-name.jpg", ) print(response.headers.get('X-My-Header')) file = response.parse() # get the object that `files.upload()` would have returned print(file.file_id) ``` -------------------------------- ### Metadata Operations Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieve metadata for files and from URLs. ```APIDOC ## Metadata ### Description Provides methods for retrieving file and URL metadata. ### Methods - **Get File Metadata** - **Method**: GET - **Endpoint**: `/v1/files/{fileId}/metadata` - **Description**: Retrieves the metadata for a specific file. - **Parameters**: - `file_id` (string) - Required - The ID of the file. - **Code Example**: `client.files.metadata.get(file_id)` - **Get Metadata from URL** - **Method**: GET - **Endpoint**: `/v1/metadata` - **Description**: Retrieves metadata for a resource located at a given URL. - **Code Example**: `client.files.metadata.get_from_url(**params)` ``` -------------------------------- ### Generate Permanent Signed URL (Python) Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Generates a signed URL that does not expire. This is useful for content that should always be accessed securely. ```python import os from imagekitio import ImageKit client = ImageKit( private_key=os.environ.get("IMAGEKIT_PRIVATE_KEY"), ) # Generate a signed URL that doesn't expire permanent_signed_url = client.helper.build_url( url_endpoint="https://ik.imagekit.io/your_imagekit_id", src="/private/secure-image.jpg", signed=True, # No expires_in means the URL won't expire ) print(permanent_signed_url) ``` -------------------------------- ### Configure Default Retries Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Set the default maximum number of retries for all requests. Set to 0 to disable retries. ```python from imagekitio import ImageKit # Configure the default for all requests: client = ImageKit( # default is 2 max_retries=0, ) ``` -------------------------------- ### Upload File Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Uploads a new file to ImageKit. This method requires parameters specifying the file content and other upload options. ```python client.files.upload(**params) ``` -------------------------------- ### Create URL Endpoint Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Creates a new URL endpoint for account management. This method allows you to programmatically add new URL endpoints. ```APIDOC ## POST /v1/accounts/url-endpoints ### Description Creates a new URL endpoint. ### Method POST ### Endpoint /v1/accounts/url-endpoints ### Parameters #### Request Body - **params** (object) - Required - Parameters for creating a URL endpoint. ### Request Example ```json { "example": "request body for create URL endpoint" } ``` ### Response #### Success Response (200) - **URLEndpointResponse** (object) - Details of the created URL endpoint. #### Response Example ```json { "example": "response body for created URL endpoint" } ``` ``` -------------------------------- ### Bulk File Operations Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Perform bulk operations on files, such as deleting, adding tags, and removing AI tags. ```APIDOC ## Bulk File Operations ### Description Provides methods for performing bulk operations on files. ### Methods - **Delete Files by IDs** - **Method**: POST - **Endpoint**: `/v1/files/batch/deleteByFileIds` - **Description**: Deletes multiple files specified by their IDs. - **Code Example**: `client.files.bulk.delete(**params)` - **Add Tags to Files** - **Method**: POST - **Endpoint**: `/v1/files/addTags` - **Description**: Adds specified tags to multiple files. - **Code Example**: `client.files.bulk.add_tags(**params)` - **Remove AI Tags from Files** - **Method**: POST - **Endpoint**: `/v1/files/removeAITags` - **Description**: Removes AI-generated tags from multiple files. - **Code Example**: `client.files.bulk.remove_ai_tags(**params)` - **Remove Tags from Files** - **Method**: POST - **Endpoint**: `/v1/files/removeTags` - **Description**: Removes specified tags from multiple files. - **Code Example**: `client.files.bulk.remove_tags(**params)` ``` -------------------------------- ### Folder Move Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Moves a folder and its contents from its current location to a new destination within your ImageKit media library. ```APIDOC ## POST /v1/bulkJobs/moveFolder ### Description Initiates a bulk job to move a folder and its contents to a new location. ### Method POST ### Endpoint /v1/bulkJobs/moveFolder ### Parameters #### Request Body - **params** (object) - Required - Contains details for the folder move operation. - **sourceFolderPath** (string) - Required - The path of the folder to move. - **destinationPath** (string) - Required - The destination path where the folder should be moved. ### Response #### Success Response (200) - **jobId** (string) - The ID of the bulk job created for the move operation. ``` -------------------------------- ### List Custom Metadata Fields Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Retrieves a list of all custom metadata fields. This method can accept parameters to filter or paginate the results. ```python client.custom_metadata_fields.list(**params) ``` -------------------------------- ### Rename Folder Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Use this method to rename a folder. It requires parameters specifying the folder to rename and its new name. ```python client.folders.rename(**params) -> FolderRenameResponse ``` -------------------------------- ### Configure Per-Request Retries Source: https://github.com/imagekit-developer/imagekit-python/blob/master/README.md Override the default retry settings for a specific request. Retries are enabled by default for certain errors. ```python with open("/path/to/your/image.jpg", "rb") as f: file_data = f.read() client.with_options(max_retries=5).files.upload( file=file_data, file_name="file-name.jpg", ) ``` -------------------------------- ### Folder Copy Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Copies a folder and its contents from one location to another within your ImageKit media library. ```APIDOC ## POST /v1/bulkJobs/copyFolder ### Description Initiates a bulk job to copy a folder and its contents to a new location. ### Method POST ### Endpoint /v1/bulkJobs/copyFolder ### Parameters #### Request Body - **params** (object) - Required - Contains details for the folder copy operation. - **sourceFolderPath** (string) - Required - The path of the folder to copy. - **destinationPath** (string) - Required - The destination path where the folder should be copied. ### Response #### Success Response (200) - **jobId** (string) - The ID of the bulk job created for the copy operation. ``` -------------------------------- ### Update File Details Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Updates the details of an existing file using its ID. This method allows modification of file properties like tags or metadata. ```python client.files.update(file_id, **params) ``` -------------------------------- ### Delete Folder Source: https://github.com/imagekit-developer/imagekit-python/blob/master/api.md Use this method to delete a folder. It requires parameters specifying the folder to delete. ```python client.folders.delete(**params) -> FolderDeleteResponse ```