Pure Python

Real-time image resizing, automatic optimization, and file uploading in Python application using ImageKit.io.

This quick start guide shows you how to integrate ImageKit into the Python application. The code samples covered here are hosted on GitHub - https://github.com/imagekit-samples/quickstart/tree/master/python.

This guide walks you through the following topics:

Setting up ImageKit Python SDK

We will create a new Python application for this tutorial and work with it.

First, we will install the imagekitio dependencies in our machine by applying the following things to our application.

Install dependencies

pip install imagekitio

Quick Examples

It loads the imagekitio dependency in our application. Before the SDK can be used, let's learn about and configure the requisite authentication parameters that need to be provided to the SDK.

Initialize SDK

In the main file of project, add your public and private API keys, as well as the URL Endpoint parameters for authentication, (You can find these keys in the Developer section of your ImageKit Dashboard)

#  Put essential values of keys [UrlEndpoint, PrivateKey, PublicKey]
from imagekitio import ImageKit
imagekit = ImageKit(
    private_key='your private_key',
    public_key='your public_key',
    url_endpoint = 'your url_endpoint'
)

The imagekitio client is configured with user-specific credentials.

Uploading images in python app

There are different ways to upload the file in imagekitio. Let's upload the remote file to imagekitio using the following code:

Example

url = "https://file-examples.com/wp-content/uploads/2017/10/file_example_JPG_100kB.jpg"
upload = imagekit.upload_file(
        file=url,
        file_name="test-url.jpg",
        options=UploadFileRequestOptions(
            response_fields=["is_private_file", "tags"],
            tags=["tag1", "tag2"]
        )
    )

The output should be like this:

# Final Result
print(upload)
<imagekitio.models.results.UploadFileResult.UploadFileResult object at 0x7f9f0ceb0dd8>

# Raw Response
print("raw", upload.response_metadata.raw)
upload remote file =>
{
    'fileId': '6311960051c0c0bdd51cff53',
    'name': 'test-url_9lQZRkh8J.jpg',
    'size': 1222,
    'versionInfo': {
        'id': '6311960051c0c0bdd51cff53',
        'name': 'Version 1'
    },
    'filePath': '/test-url_9lQZRkh8J.jpg',
    'url': 'https://ik.imagekit.io/your_imagekit_id/test-url_9lQZRkh8J.jpg',
    'fileType': 'non-image',
    'tags': ['tag1', 'tag2'],
    'AITags': None,
    'isPrivateFile': False
}

Congratulation, the file was uploaded successfully.

Generating URL for rendering images in python app

Here, declare a variable to store the image URL generated by the SDK. Like this:

Example


image_url = imagekit.url({
            "path": "/default-image.jpg"
        }
    )

Now, image_url has the URL https://ik.imagekit.io/<your_imagekit_id>/default-image.jpg stored in it. This fetches the image from the URL stored in image_url.

Open the URL in the browser. It should now display this default image in its full size:

Common image manipulation in Python App

Let’s now learn how to manipulate images using ImgeKit transformations.

Height and width manipulation

To resize an image or video along with its height or width, we need to pass the transformation option in imageKit.url() method.

Let's resize the default image to 200px height and width:

Example

image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"height": "200", "width": "200", "raw": "ar-4-3,q-40"}],
        }
    )

Transformation URL:

https://ik.imagekit.io/fl0osl7rq9/tr:h-200,w-200,raw-ar-4-3,q-40/default-image.jpg

Refresh your browser with a new url to get the resized image.

The imageKit.url() method accepts the following parameters.

OptionDescription

urlEndpoint

Optional. The base URL is to be appended before the path of the image. If not specified, the URL Endpoint specified at the time of SDK initialization is used. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/

path

Conditional. This is the path on which the image exists. For example, /path/to/image.jpg. Either the path or src parameter needs to be specified for URL generation.

src

Conditional. This is the complete URL of an image already mapped to ImageKit. For example, https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg. Either the path or src parameter needs to be specified for URL generation.

transformation

Optional. An array of objects specifying the transformation to be applied in the URL. The transformation name and the value should be specified as a key-value pair in the object. Different steps of a chained transformation can be specified as different objects of the array. The complete List of supported transformations in the SDK and some examples of using them are given later. If you use a transformation name that is not specified in the SDK, it gets applied as it is in the URL.

transformationPosition

Optional. The default value is path, which places the transformation string as a path parameter in the URL. It can also be specified as query, which adds the transformation string as the query parameter tr in the URL. The transformation string is always added as a query parameter if you use the src parameter to create the URL.

queryParameters

Optional. These are the other query parameters that you want to add to the final URL. These can be any query parameters and are not necessarily related to ImageKit. Especially useful if you want to add some versioning parameters to your URLs.

signed

Optional. Boolean. The default value is false. If set to true, the SDK generates a signed image URL adding the image signature to the image URL.

expireSeconds

Optional. Integer. It is used along with the signed parameter. It specifies the time in seconds from now when the signed URL will expire. If specified, the URL contains the expiry timestamp in the URL, and the image signature is modified accordingly.

Applying Chained Transformations, Common Image Manipulations & Signed URL

This section covers the basics:

The Python SDK gives a name to each transformation parameter e.g. height for h and width for w parameter. It makes your code more readable. See the Full List of supported transformations.

👉 If the property does not match any of the available options, it is added as it is.

[
    'effectGray' => 'e-grayscale'
]
# and
[
    'e-grayscale' => ''
]
# works the same

👉 Note that you can also use the h and w parameters instead of height and width.

For more examples, check the Demo Application.

1. Chained Transformations

Chained transformations provide a simple way to control the sequence in which transformations are applied.

Chained Transformations as a query parameter

Let's try it out by resizing an image, then rotating it:

Example

image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"height": "200", "width": "200"}],
            "transformation_position": "query",
        }
    )

Transformation URL:

https://ik.imagekit.io/fl0osl7rq9/default-image.jpg?tr=h-200%2Cw-200

Output Image:

Now, rotate the image by 90 degrees.

Example

image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"height": "300", "width": "200"}, {"rt": "90"}],
        }
    )

Chained Transformation URL:

https://ik.imagekit.io/fl0osl7rq9/tr:h-300,w-200:rt-90/default-image.jpg

Output Image:

Let's flip the order of transformation and see what happens.

Example

image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"rt": "90"}, {"height": "300", "width": "200"}],
        }
    )

Chained Transformation URL:

https://ik.imagekit.io/fl0osl7rq9/tr:rt-90:h-300,w-200/default-image.jpg

Output Image:

2. Image enhancement and color manipulation

Some transformations like Contrast stretch , Sharpen and Unsharp mask can be added to the URL with or without any other value. To use such transforms without specifying a value, specify the value as "-" in the transformation object. Otherwise, specify the value that you want to be added to this transformation.

Example

image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [
                {
                    "format": "jpg",
                    "progressive": "true",
                    "effect_sharpen": "-",
                    "effect_contrast": "1",
                }
            ],
        }
    )

Transformation URL:

https://ik.imagekit.io/fl0osl7rq9/tr:f-jpg,pr-true,e-sharpen,e-contrast-1/default-image.jpg

Output Image:

3. Resizing images

Let's resize the image to a width of 200 and a height of 200. Check detailed instructions on Resize, Crop, and Other Common Transformations

Example

image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"height": "200", "width": "200"}],
        }
    )

Transformation URL:

https://ik.imagekit.io/fl0osl7rq9/tr:h-200,w-200/default-image.jpg

Output Image:

4. Quality manipulation

You can use the Quality Parameter to change quality like this.

Example

image_url = imagekit.url(
        {
            "path": "/default-image.jpg",
            "transformation": [{"quality": "40"}],
        }
    )

Transformation URL:

https://ik.imagekit.io/fl0osl7rq9/tr:q-40/default-image.jpg

Output Image:

5. Adding overlays

ImageKit.io enables you to apply overlays to images and videos using the raw parameter with the concept of layers. The raw parameter facilitates incorporating transformations directly in the URL. A layer is a distinct type of transformation that allows you to define an asset to serve as an overlay, along with its positioning and additional transformations.

Text as overlays

You can add any text string over a base video or image using a text layer (l-text).

For example:

image_url = imagekit.url({
    "path": "/default-image",
    "url_endpoint": "https://ik.imagekit.io/your_imagekit_id/endpoint/",
    "transformation": [{
        "height": "300",
        "width": "400",
        "raw": "l-text,i-Imagekit,fs-50,l-end"
    }],
})

Sample Result URL

https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-text,i-Imagekit,fs-50,l-end/default-image.jpg

Output Image:

Image as overlays

You can add an image over a base video or image using an image layer (l-image).

For example:

image_url = imagekit.url({
    "path": "/default-image",
    "url_endpoint": "https://ik.imagekit.io/your_imagekit_id/endpoint/",
    "transformation": [{
        "height": "300",
        "width": "400",
        "raw": "l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end"
    }],
})

Sample Result URL

https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-default-image.jpg,w-100,b-10_CDDC39,l-end/default-image.jpg

Output Image:

Solid color blocks as overlays

You can add solid color blocks over a base video or image using an image layer (l-image).

For example:

image_url = imagekit.url({
    "path": "/default-image.jpg",
    "url_endpoint": "https://ik.imagekit.io/your_imagekit_id/endpoint/",
    "transformation": [{
        "height": "300",
        "width": "400",
        "raw": "l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end"
    }],
})

Sample Result URL

https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end/default-image.jpg

Output Image:

List of supported transformations

See the complete list of image and video transformations supported in ImageKit. The SDK gives a name to each transformation parameter e.g. height for h and width for w parameter. It makes your code more readable. If the property does not match any of the following supported options, it is added as it is.

If you want to generate transformations in your application and add them to the URL as it is, use the raw parameter.

Supported Transformation NameTranslates to parameter

height

h

width

w

aspect_ratio

ar

quality

q

crop

c

crop_mode

cm

x

x

y

y

focus

fo

format

f

radius

r

background

bg

border

b

rotation

rt

blur

bl

named

n

progressive

pr

lossless

lo

trim

t

metadata

md

color_profile

cp

default_image

di

dpr

dpr

effect_sharpen

e-sharpen

effect_usm

e-usm

effect_contrast

e-contrast

effect_gray

e-grayscale

effect_shadow

e-shadow

effect_gradient

e-gradient

original

orig

raw

replaced by the parameter value

Server-side File Upload

The SDK provides a simple interface using the imagekit.upload_file() method to upload files to the ImageKit Media Library.

Example

result = imagekit.upload_file(
        file=open("sample.jpg", "rb"),
        file_name="test-file.jpg",
    )

Response

# Final Result
print(upload)
<imagekitio.models.results.UploadFileResult.UploadFileResult object at 0x7f9f0ceb0dd8>

# Raw Response
{
    'fileId': '631197af51c0c0bdd51f77da',
    'name': 'test-file_X4nk4kIuC.jpg',
    'size': 59,
    'versionInfo': {
        'id': '631197af51c0c0bdd51f77da',
        'name': 'Version 1'
    },
    'filePath': '/test-file_X4nk4kIuC.jpg',
    'url': 'https://ik.imagekit.io/zv3rkhsym/test-file_X4nk4kIuC.jpg',
    'fileType': 'non-image',
    'AITags': None
}

Optional Parameters

Please refer to Server Side File Upload - Request Structure for a detailed explanation of mandatory and optional parameters.

Example

result = imagekit.upload_file(
        file=open("sample.jpg", "rb"),
        file_name="testing-file.jpg",
        options=UploadFileRequestOptions(
            use_unique_file_name=False,
            tags=["tag-1", "tag-2"],
            folder="/testing-folder/",
            is_private_file=True,
            custom_coordinates="10,10,20,20",
            response_fields=["is_private_file", "tags"],
            extensions=[
                {"name": "remove-bg", "options": {"add_shadow": True, "bg_color": "pink"}},
                {"name": "google-auto-tagging", "minConfidence": 80, "maxTags": 10}
            ],
            webhook_url="url",
            overwrite_file=True,
            overwrite_ai_tags=False,
            overwrite_tags=False,
            overwrite_custom_metadata=True,
            custom_metadata={"test": 11}
            transformation = { 
                "pre": 'l-text,i-Imagekit,fs-50,l-end',
                "post": [{ "type": 'transformation', "value": 'w-100' }] 
            }
        ),
    )

ImageKit Media API

The SDK provides a simple interface for all the following Media APIs to manage your files.

1. List and Search Files

This API can list all the uploaded files and folders in your ImageKit.io media library.

Refer to the List and Search File API for a better understanding of the Request & Response Structure.

Example

list_files = imagekit.list_files()

Applying Filters

Filter out the files with an object specifying the parameters.

list_files = imagekit.list_files(options=ListAndSearchFileRequestOptions(type="file", sort="ASC_CREATED", path="/",
                                                                        search_query="created_at >= '2d' OR size < '2mb' OR format='png'",
                                                                        file_type="all", limit=5, skip=0,
                                                                        tags="tag-1, tag-2, tag-3"))
# Final Result
print(list_files)

# Raw Response
print(list_files.response_metadata.raw)

# print the first file's ID
print(list_files.list[0].file_id)

In addition, you can fine-tune your query by specifying various filters by generating a query string in a Lucene-like syntax and providing this generated string as the value of the searchQuery.

list_files = imagekit.list_files(options=ListAndSearchFileRequestOptions(search_query="(size < '1mb' AND width < 500) OR (tags IN ['tag-1', 'tag-2'])"))   

Detailed documentation can be found here for Advance Search Queries.

2. Get File Details

This API can get you all the details and attributes of the current version of the file.

Refer to the Get File Details API for a better understanding of the Request & Response Structure.

Example

details = imagekit.get_file_details(file_id="file_id")
# Final Result
print(details)

# Raw Response
print(details.response_metadata.raw)

# print that file's id
print(details.file_id)

3. Get File Versions

This API can get you all the versions of the file.

Refer to the Get File Versions API for a better understanding of the Request & Response Structure.

Example

file_versions = imagekit.get_file_versions(file_id='file_id')
# Final Result
print(file_versions)
# Raw Response
print(file_versions.response_metadata.raw)

# print that file's version id
print(file_versions.list[0].version_info.id)

4. Get File Version Details

This API can get you all the details and attributes for the provided version of the file.versionID can be found in the following APIs as id within the versionInfo parameter:

Refer to the Get File Version Details API for a better understanding of the Request & Response Structure.

Example

file_versions_details = imagekit.get_file_version_details(file_id='file_id', version_id='version_id')
# Final Result
print(file_versions_details)

# Raw Response
print(file_versions_details.response_metadata.raw)

# print that file's id
print(file_versions_details.file_id)

# print that file's version id
print(file_versions_details.version_info.id)

5. Update File Details

Update file details such as tags, customCoordinates attributes, remove existing AITags, and apply extensions using Update File Details API. This operation can only be performed on the current version of the file.

Refer to the Update File Details API for better understanding about the Request & Response Structure.

Example

updated_detail = imagekit.update_file_details(
        file_id="file_id",
        options=UpdateFileRequestOptions(remove_ai_tags=['remove-ai-tag-1', 'remove-ai-tag-2'],
                                         webhook_url="url",
                                         extensions=[
                                             {"name": "remove-bg", "options": {"add_shadow": True, "bg_color": "red"}},
                                             {"name": "google-auto-tagging", "minConfidence": 80, "maxTags": 10}],
                                         tags=["tag1", "tag2"], custom_coordinates="10,10,100,100",
                                         custom_metadata={"test": 11})
)
# Final Result
print(updated_detail)

# Raw Response
print(updated_detail.response_metadata.raw)

# print that file's id
print(updated_detail.file_id)

6. Add Tags (Bulk) API

Add tags to multiple files in a single request. The method accepts an object which contains an array of fileIds of the files and an array of tags that have to be added to those files.

Refer to the Add Tags (Bulk) API for a better understanding of the Request & Response Structure.

Example

tags = imagekit.add_tags(file_ids=['file_id_1', 'file_id_2'], tags=['tag-to-add-1', 'tag-to-add-2'])
# Final Result
print(tags)

# Raw Response
print(tags.response_metadata.raw)

# list successfully updated file ids
print(tags.successfully_updated_file_ids)

# print the first file's id
print(tags.successfully_updated_file_ids[0])

7. Remove Tags (Bulk) API

Remove tags from multiple files in a single request. The method accepts an object which contains an array of fileIds of the files and an array of tags that have to be removed from those files.

Refer to the Remove Tags (Bulk) API for a better understanding of the Request & Response Structure.

Example

remove_tags = imagekit.remove_tags(file_ids=['file_id_1', 'file_id_2'], tags=['tag-to-remove-1', 'tag-to-remove-2'])
# Final Result
print(remove_tags)

# Raw Response
print(remove_tags.response_metadata.raw)

# list successfully updated file ids
print(remove_tags.successfully_updated_file_ids)

# print the first file's id
print(remove_tags.successfully_updated_file_ids[0])

8. Remove AI Tags (Bulk) API

Remove AI tags from multiple files in a single request. The method accepts an object which contains an array of fileIds of the files and an array of AITags that have to be removed from those files.

Refer to the Remove AI Tags (Bulk) API for a better understanding of the Request & Response Structure.

Example

remove_ai_tags = imagekit.remove_ai_tags(file_ids=['file_id_1', 'file_id_2'], ai_tags=['ai-tag-to-remove-1', 'ai-tag-to-remove-2'])
# Final Result
print(remove_ai_tags)

# Raw Response
print(remove_ai_tags.response_metadata.raw)

# list successfully updated file ids
print(remove_ai_tags.successfully_updated_file_ids)

# print the first file's id
print(remove_ai_tags.successfully_updated_file_ids[0])

9. Delete File API

You can programmatically delete uploaded files in the media library using delete file API.

If a file or specific transformation has been requested in the past, then the response is cached. Deleting a file does not purge the cache. You can purge the cache using Purge Cache API.

Refer to the Delete File API for better understanding about the Request & Response Structure.

Basic Usage

delete_file = imagekit.delete_file(file_id='file_id')
# Final Result
print(delete_file)

# Raw Response
print(delete_file.response_metadata.raw)

10. Delete File Version API

You can programmatically delete the uploaded file version in the media library using the delete file version API.

You can delete only the non-current version of a file.

Refer to the Delete File Version API for a better understanding of the Request & Response Structure.

Example

delete_file_version = imagekit.delete_file_version(file_id="file_id", version_id="version_id")
# Final Result
print(delete_file_version)

# Raw Response
print(delete_file_version.response_metadata.raw)

11. Delete Files (Bulk) API

Deletes multiple files and their versions from the media library.

Refer to the Delete Files (Bulk) API for a better understanding of the Request & Response Structure.

Example

bulk_file_delete = imagekit.bulk_file_delete(file_ids=['file-id-1', 'file-id-2'])
# Final Result
print(bulk_file_delete)

# Raw Response
print(bulk_file_delete.response_metadata.raw)

# list successfully deleted file ids
print(bulk_file_delete.successfully_deleted_file_ids)

# print the first file's id
print(bulk_file_delete.successfully_deleted_file_ids[0])

12. Copy File API

This will copy a file from one folder to another.

If any file at the destination has the same name as the source file, then the source file and its versions (if includeFileVersions is set to true) will be appended to the destination file version history.

Refer to the Copy File API for a better understanding of the Request & Response Structure.

Basic Usage

copy_file = imagekit.copy_file(options=CopyFileRequestOptions(source_file_path="/your_file_name.jpg",
                                                              destination_path="/test",
                                                              include_file_versions=True))
# Final Result
print(copy_file)

# Raw Response
print(copy_file.response_metadata.raw)

13. Move File API

This will move a file and all its versions from one folder to another.

If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file.

Refer to the Move File API for a better understanding of the Request & Response Structure.

Example

move_file = imagekit.move_file(options=MoveFileRequestOptions(source_file_path="/your_file_name.jpg",
                                                              destination_path="/test"))
# Final Result
print(move_file)

# Raw Response
print(move_file.response_metadata.raw)

14. Rename File API

You can programmatically rename an already existing file in the media library using Rename File API. This operation would rename all file versions of the file.

The old URLs will stop working. The file/file version URLs cached on CDN will continue to work unless a purge is requested.

Refer to the Rename File API for a better understanding of the Request & Response Structure.

Example

# Purge Cache would default to false

rename_file = imagekit.rename_file(options=RenameFileRequestOptions(file_path="/file_path.jpg",
                                                                        new_file_name="new_file_name.jpg"))
# Final Result
print(rename_file)

# Raw Response
print(rename_file.response_metadata.raw)

# print the purge request id
print(rename_file.purge_request_id)

When purgeCache is set to true, response will return purgeRequestId. This purgeRequestId can be used to get the purge request status.

rename_file = imagekit.rename_file(options=RenameFileRequestOptions(file_path="/file_path.jpg",
                                                                    new_file_name="new_file_name.jpg",
                                                                    purge_cache=True))
# Final Result
print(rename_file)

# Raw Response
print(rename_file.response_metadata.raw)

# print the purge request id
print(rename_file.purge_request_id)

15. Restore file Version API

This will restore file version to a different version of a file. Refer to the Restore file Version API for a better understanding of the Request & Response Structure.

Example

restore_file_version = imagekit.restore_file_version(file_id="file_id", version_id="version_id")
# Final Result
print(restore_file_version)

# Raw Response
print(restore_file_version.response_metadata.raw)

# print that file's id
print(restore_file_version.file_id)

16. Create Folder API

This will create a new folder. You can specify the folder name and location of the parent folder where this new folder should be created.

Refer to the Create Folder API for a better understanding of the Request & Response Structure.

Example

create_folder = imagekit.create_folder(options=CreateFolderRequestOptions(folder_name="test",
                                                                          parent_folder_path="/"))
# Final Result
print(create_folder)

# Raw Response
print(create_folder.response_metadata.raw)

17. Delete Folder API

This will delete the specified folder and all nested files, their versions & folders. This action cannot be undone.

Refer to the Delete Folder API for a better understanding of the Request & Response Structure.

Example

delete_folder = imagekit.delete_folder(options=DeleteFolderRequestOptions(folder_path="/test/demo"))
# Final Result
print(delete_folder)

# Raw Response
print(delete_folder.response_metadata.raw)

18. Copy Folder API

This will copy one folder into another.

If any folder at the destination has the same name as the source folder, then the source folder and its versions (if includeFileVersions is set to true) will be appended to the destination folder version history.

Refer to the Copy Folder API for a better understanding of the Request & Response Structure.

Example

copy_folder = imagekit.copy_folder(options=CopyFolderRequestOptions(source_folder_path='/source_folder_path',
                                                                    destination_path='/destination/path',
                                                                    include_file_versions=True))
# Final Result
print(copy_folder)

# Raw Response
print(copy_folder.response_metadata.raw)

# print the job's id
print(copy_folder.job_id)

19. Move Folder API

This will move one folder into another. The selected folder, its nested folders, files, and their versions are moved in this operation.

If any file at the destination has the same name as the source file, then the source file and its versions will be appended to the destination file version history.

Refer to the Move Folder API for a better understanding of the Request & Response Structure.

Example

move_folder = imagekit.move_folder(options=MoveFolderRequestOptions(source_folder_path="/source-folder",
                                                                    destination_path="/"))
# Final Result
print(move_folder)

# Raw Response
print(move_folder.response_metadata.raw)

# print the job's id
print(move_folder.job_id)

20. Bulk Job Status API

This endpoint allows you to get the status of a bulk operation e.g. Copy Folder API or Move Folder API.

Refer to the Bulk Job Status API for a better understanding of the Request & Response Structure.

Example

job_status = imagekit.get_bulk_job_status(job_id="job_id")
# Final Result
print(job_status)

# Raw Response
print(job_status.response_metadata.raw)

# print the job's id
print(job_status.job_id)

# print the status
print(job_status.status)

21. Purge Cache API

This will purge CDN and ImageKit.io's internal cache. In response requestId is returned which can be used to fetch the status of the submitted purge request with Purge Cache Status API.

Refer to the Purge Cache API for a better understanding of the Request & Response Structure.

Example

purge_cache = imagekit.purge_cache(file_url="file_url")
# Final Result
print(purge_cache)

# Raw Response
print(purge_cache.response_metadata.raw)

# print the purge file cache request id
print(purge_cache.request_id)

22. Purge Cache Status API

Get the purge cache request status using the requestId returned when a purge cache request gets submitted with Purge Cache API

Refer to the Purge Cache Status API for a better understanding of the Request & Response Structure.

Example

purge_cache_status = imagekit.get_purge_cache_status(purge_cache_id="request_id")
# Final Result
print(purge_cache_status)

# Raw Response
print(purge_cache_status.response_metadata.raw)

# print the purge file cache status
print(purge_cache_status.status)

23. Get File Metadata API (From File ID)

Get the image EXIF, pHash, and other metadata for uploaded files in the ImageKit.io media library using this API.

Refer to the Get image metadata for uploaded media files API for a better understanding of the Request & Response Structure.

Example

file_metadata = imagekit.get_metadata(file_id="file_id")
# Final Result
print(file_metadata)

# Raw Response
print(file_metadata.response_metadata.raw)

# print the file metadata fields
print(file_metadata.width)
print(file_metadata.exif.image.x_resolution)

24. Get File Metadata API (From Remote URL)

Get image EXIF, pHash, and other metadata from ImageKit.io powered remote URL using this API.

Refer to the Get image metadata from remote URL API for a better understanding of the Request & Response Structure.

Example

remote_file_url_metadata = imagekit.get_remote_file_url_metadata(remote_file_url="image_url")
# Final Result
print(remote_file_url_metadata)

# Raw Response
print(remote_file_url_metadata.response_metadata.raw)

# print the file metadata fields
print(remote_file_url_metadata.width)
print(remote_file_url_metadata.exif.image.x_resolution)

Custom Metadata Fields API

Imagekit.io allows you to define a schema for your metadata keys and the value filled against that key will have to adhere to those rules. You can Create, Read, Update and Delete custom metadata rules and update your file with custom metadata value in File update API or File Upload API.

For a detailed explanation refer to the Custom Metadata Documentaion.

1. Create Fields

Create a Custom Metadata Field with this API.

Refer to the Create Custom Metadata Fields API for a better understanding of the Request & Response Structure.

Example

create_custom_metadata_fields_number = imagekit.create_custom_metadata_fields(
    options=CreateCustomMetadataFieldsRequestOptions(
                                                        name="test",
                                                        label="test",
                                                        schema=CustomMetadataFieldsSchema(
                                                            type=CustomMetaDataTypeEnum.Number,
                                                            min_value=100,
                                                            max_value=200
                                                        )
                                                     )
)
# Final Result
print(create_custom_metadata_fields_number)

# Raw Response
print(create_custom_metadata_fields_number.response_metadata.raw)

# print the id of created custom metadata fields
print(create_custom_metadata_fields_number.id)

# print the schema's type of created custom metadata fields
print(create_custom_metadata_fields_number.schema.type)

MultiSelect type Exmample:

create_custom_metadata_fields_multi_select = imagekit.create_custom_metadata_fields(
    options=CreateCustomMetadataFieldsRequestOptions(
                                                        name="test-MultiSelect",
                                                        label="test-MultiSelect",
                                                        schema=CustomMetadataFieldsSchema(
                                                            type=CustomMetaDataTypeEnum.MultiSelect,
                                                            is_value_required=True,
                                                            default_value=[
                                                                "small", 30,
                                                                True],
                                                            select_options=["small",
                                                                        "medium",
                                                                        "large", 30, 40,
                                                                        True]
                                                        )
                                                    )
)
# Final Result
print(create_custom_metadata_fields_multi_select)

# Raw Response
print(create_custom_metadata_fields_multi_select.response_metadata.raw)

# print the name of created custom metadata fields
print(create_custom_metadata_fields_multi_select.name)

# print the schema's select options of created custom metadata fields
print(create_custom_metadata_fields_multi_select.schema.select_options)

Check for the Allowed Values In The Schema.

2. Get Fields

Get a list of all the custom metadata fields. if includeDeleted is passed and set to true, the List will include deleted fields also.

Refer to the Get Custom Metadata Fields API for a better understanding of the Request & Response Structure.

Example

get_custom_metadata_fields = imagekit.get_custom_metadata_fields() # include_deleted would be False by default
# Final Result
print(get_custom_metadata_fields)

# Raw Response
print(get_custom_metadata_fields.response_metadata.raw)

# print the first customMetadataField's id
print(get_custom_metadata_fields.list[0].id)
get_custom_metadata_fields = imagekit.get_custom_metadata_fields(include_deleted=True)
# Final Result
print(get_custom_metadata_fields)

# Raw Response
print(get_custom_metadata_fields.response_metadata.raw)

# print the first customMetadataField's id
print(get_custom_metadata_fields.list[0].id)

3. Update Fields

Update the label or schema of an existing custom metadata field.

Refer to the Update Custom Metadata Fields API for a better understanding of the Request & Response Structure.

Example

update_custom_metadata_fields = imagekit.update_custom_metadata_fields(
    field_id = "field_id",
    options = UpdateCustomMetadataFieldsRequestOptions(
        label = "test-update",
        schema = CustomMetadataFieldsSchema(
            min_value = 100,
            max_value = 200
        )
    )
)
# Final Result
print(update_custom_metadata_fields)

# Raw Response
print(update_custom_metadata_fields.response_metadata.raw)

# print the label of updated custom metadata fields
print(update_custom_metadata_fields.label)

# print the schema's min value of updated custom metadata fields
print(update_custom_metadata_fields.schema.min_value)

Check for the Allowed Values In The Schema.

4. Delete Fields

Delete a custom metadata field.

Refer to the Delete Custom Metadata Fields API for a better understanding of the Request & Response Structure.

Example

delete_custom_metadata_field = imagekit.delete_custom_metadata_field(
    field_id="field_id")
# Final Result
print(delete_custom_metadata_field)

# Raw Response
print(delete_custom_metadata_field.response_metadata.raw)

What's next

The possibilities for image manipulation and optimization with ImageKit are endless. Learn more about it here:

Last updated