Package: imagekitio
ImageKit.io Python SDKPython SDK forImageKitimplements the new APIs and interface for different file operations.ImageKit is complete media storage, optimization, and transformation solution that comes with animage and video CDN. It can be integrated with your existing infrastructure - storage like AWS S3, web servers, your CDN, and custom domain names, allowing you to deliver optimized images in minutes with minimal code changes.Supported Python Versions: >=3.6Table of contents -InstallationInitializationChange LogUsageURL GenerationFile UploadFile ManagementUtility FunctionsHandling errorsDevelopmentTestsSampleSupportLinksInstallationGo to your terminal and type the following command.pipinstallimagekitioInitializationfromimagekitioimportImageKitimagekit=ImageKit(private_key='your_private_key',public_key='your_public_key',url_endpoint='your_url_endpoint')Change logThis document presents a list of changes that break the existing functionality of previous versions. We try to minimize these disruptions, but they are sometimes unavoidable, especially in significant updates. Therefore, versions are marked semantically and tagged as major upgrades whenever such breaking changes occur.Breaking History:Changes from3.2.0 -> 4.0.0are listed belowOverlay syntax updateIn version 4.0.0, we've removed the old overlay syntax parameters for transformations, such asoi,ot,obg, andmore. These parameters are deprecated and will start returning errors when used in URLs. Please migrate to the new layers syntax that supports overlay nesting, provides better positional control, and allows more transformations at the layer level. You can start withexamplesto learn quickly.You can migrate to the new layers syntax using therawtransformation parameter.Changes from2.2.8 -> 3.0.0are listed belowThrow an Error:What changedBefore the upgrade, anerrordict was coming in the return object of any function call. Now, SDK throws an exception in case of an error.Who is affected?This affects any development in your software that calls APIs from ImageKit IO and handles errors based on what's returned.How should I update my code?To avoid failures in an application, you could handle errors asdocumented hereUsageYou can use this Python SDK for three different kinds of methods:URL GenerationFile UploadFile ManagementUtility FunctionsURL Generation1. Using Image path and endpoint (hostname)This method allows you to create a URL using the relative file path where the image exists and the URL
endpoint(url_endpoint) you want to use to access the image. You can refer to the documentationhereto read more about URL endpoints
in ImageKit and the section aboutimage originsto understand
about paths with different kinds of origins.The file can be an image, video, or any other static file supported by ImageKit.imagekit_url=imagekit.url({"path":"/default-image.jpg","url_endpoint":"https://ik.imagekit.io/your_imagekit_id/endpoint/","transformation":[{"height":"300","width":"400","raw":"ar-4-3,q-40"}],})Sample Result URL -https://ik.imagekit.io/your_imagekit_id/endpoint/tr:h-300,w-400,ar-4-3,q-40/default-image.jpg2. Using full image URLThis method allows you to add transformation parameters to an absolute URL using thesrcparameter. This method should be
used if you have the complete image URL stored in your database.image_url=imagekit.url({"src":"https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg","transformation":[{"height":"300","width":"400","raw":"ar-4-3,q-40"}]})Sample Result URL -https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400%2Car-4-3%2Cq-40The.url()method accepts the following parameters.OptionDescriptionurl_endpointOptional. The prepended base URL before the path of the image. If not specified, the URL Endpoint specified during SDK initialization gets used. For example,https://ik.imagekit.io/your_imagekit_id/endpoint/pathConditional. A path at which the image exists. For example,/path/to/image.jpg. Specify apathorsrcparameter for URL generation.srcConditional. Complete URL of an image already mapped to ImageKit. For example,https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg. Specify apathorsrcparameter for URL generation.transformationOptional. Specify an array of objects with name and the value in key-value pair to apply transformation params in the URL. Append different steps of achained transformationas different objects of the array. This document includes a complete list of supported transformations in the SDK with some examples. If one uses an unspecified transformation name, it gets applied as it is in the URL.transformation_positionOptional. The default value ispath, which places the transformation string as a path parameter in the URL. One can also specify it as a query, which adds the transformation string as the query parametertrin the URL. Suppose one uses thesrcparameter to create the URL. In that case, the transformation string is always a query parameter.query_parametersOptional. These are the other query parameters that one wants to add to the final URL. These can be any query parameters and are not necessarily related to ImageKit. Especially useful if one wants to add some versioning parameter to their URLs.signedOptional. Boolean. The default isfalse. If set totrue, the SDK generates a signed image URL adding the image signature to the image URL. One can only use this if they create the URL with theurl_endpointandpathparameters, not thesrcparameter.expire_secondsOptional. Integer. Used along with thesignedparameter to specify the time in seconds fromnowwhen the URL should expire. If specified, the URL contains the expiry timestamp, and the image signature is modified accordingly.Examples of generating URLs1. Chained Transformations as a query parameterimage_url=imagekit.url({"path":"/default-image.jpg","url_endpoint":"https://ik.imagekit.io/your_imagekit_id/endpoint/","transformation":[{"height":"300","width":"400"},{"rotation":90}],"transformation_position":"query"})Sample Result URL -https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=h-300%2Cw-400%3Art-902. Sharpening, contrast transform and progressive JPG imageAdd transformations likeSharpeningto the URL with or without any other value. To use such transforms without specifying a value, set it as "-" in the transformation object. Otherwise, use the value that one wants to add to this transformation.image_url=imagekit.url({"src":"https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg","transformation":[{"format":"jpg","progressive":"true","effect_sharpen":"-","effect_contrast":"1"}]})Sample Result URL -# Note that because the `src` parameter is in effect, the transformation string gets added as a query parameter `tr`

https://ik.imagekit.io/your_imagekit_id/endpoint/default-image.jpg?tr=f-jpg%2Cpr-true%2Ce-sharpen%2Ce-contrast-13. Signed URL that expires in 300 seconds with the default URL endpoint and other query parametersimage_url=imagekit.url({"path":"/default-image.jpg","query_parameters":{"p1":"123","p2":"345"},"transformation":[{"height":"300","width":"400"}],"signed":True,"expire_seconds":300})Sample Result URL -https://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400/default-image.jpg?p1=123&p2=345&ik-t=1658899345&ik-s=8f03aca28432d4e87f697a48143efb4497bbed9e4. Adding overlaysImageKit.io enables you to apply overlays toimagesandvideosusing the raw parameter with the concept oflayers. 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 overlaysYou 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 URLhttps://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-text,i-Imagekit,fs-50,l-end/default-image.jpgImage as overlaysYou 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 URLhttps://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.jpgSolid color blocks as overlaysYou can add solid color blocks over a base video or image using an image layer (l-image).For example:image_url=imagekit.url({"path":"/img/sample-video","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 URLhttps://ik.imagekit.io/your_imagekit_id/tr:h-300,w-400,l-image,i-ik_canvas,bg-FF0000,w-300,h-100,l-end/img/sample-video.mp45. Arithmetic expressions in transformationsImageKit allows use ofarithmetic expressionsin certain dimension and position-related parameters, making media transformations more flexible and dynamic.For example:image_url=imagekit.url({"path":"/default-image.jpg","url_endpoint":"https://ik.imagekit.io/your_imagekit_id/endpoint/","transformation":[{"height":"ih_div_2","width":"iw_div_4","border":"cw_mul_0.05_yellow"}],})Sample Result URLhttps://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=w-iw_div_4,h-ih_div_2,b-cw_mul_0.05_yellowList of transformationsThe complete list of transformations supported and their usage in ImageKit is availablehere.
The SDK gives a name to each transformation parameter, making the code simpler, more straightforward, and readable. If a transformation is supported in ImageKit, though it cannot be found in the table below, then use the transformation code from ImageKit docs as the name when using theURLfunction.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 parameterheighthwidthwaspect_ratioarqualityqcropccrop_modecmxxyyfocusfoformatfradiusrbackgroundbgborderbrotationrtblurblnamednprogressiveprlosslesslotrimtmetadatamdcolor_profilecpdefault_imagedidprdpreffect_sharpene-sharpeneffect_usme-usmeffect_contraste-contrasteffect_graye-grayscaleeffect_shadowe-shadoweffect_gradiente-gradientoriginalorigrawreplaced by the parameter valueFile UploadThe SDK provides a simple interface using the.upload_file()method to upload files to the ImageKit Media library. It
accepts all the parameters supported by
theImageKit Upload API.Theupload_file()method requires at least thefileas (URL/Base64/Binary) and thefile_nameparameter to upload a
file. The method returns a dict data in case of success, or it will throw a custom exception in case of failure.
Use theoptionsparameter to pass other parameters supported by
theImageKit Upload API. Use the same
parameter name as specified in the upload API documentation.Simple usagefromimagekitio.models.UploadFileRequestOptionsimportUploadFileRequestOptionsextensions=[{'name':'remove-bg','options':{'add_shadow':True,'bg_color':'pink'}},{'name':'google-auto-tagging','minConfidence':80,'maxTags':10}]transformation={'pre':'l-text,i-Imagekit,fs-50,l-end','post':[{'type':'transformation','value':'w-100'}]}options=UploadFileRequestOptions(use_unique_file_name=False,tags=['abc','def'],folder='/testing-python-folder/',is_private_file=False,custom_coordinates='10,10,20,20',response_fields=['tags','custom_coordinates','is_private_file','embedded_metadata','custom_metadata'],extensions=extensions,webhook_url='https://webhook.site/c78d617f-33bc-40d9-9e61-608999721e2e',overwrite_file=True,overwrite_ai_tags=False,overwrite_tags=False,overwrite_custom_metadata=True,custom_metadata={'testss':12},transformation=transformation)result=imagekit.upload_file(file='<url|base_64|binary>',# requiredfile_name='my_file_name.jpg',# requiredoptions=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print that uploaded file's IDprint(result.file_id)If the upload succeeds, theresultwill be theUploadFileResultclass.If the upload fails, the custom exception will be thrown with:response_helpfor any kind of helpresponse_metadatawithraw,http_status_codeandheadersmessagecan be called to get the error message received from ImageKit's servers.File ManagementThe SDK provides a simple interface for all
themedia APIs mentioned hereto manage your files. This also returnsresult.1. List & Search FilesAccepts an object specifying the parameters used to list and search files. All parameters specified
in
thedocumentation herecan be passed with the correct values to get the results.fromimagekitio.models.ListAndSearchFileRequestOptionsimportListAndSearchFileRequestOptionsoptions=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='Software, Developer, Engineer',)result=imagekit.list_files(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the first file's IDprint(result.list[0].file_id)2. Get File DetailsAccepts the file ID and fetches the details as per
theAPI documentation herefile_id="your_file_id"result=imagekit.get_file_details(file_id=file_id)# file_id required# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print that file's idprint(result.file_id)3. Get File VersionsAccepts the file ID and fetches the details as per
theAPI documentation herefile_id="your_file_id"result=imagekit.get_file_versions(file_id=file_id)# file_id required# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print that file's version idprint(result.list[0].version_info.id)4. Get File Version detailsAccepts thefile_idandversion_idand fetches the details as per
theAPI documentation hereresult=imagekit.get_file_version_details(file_id='file_id',version_id='version_id')# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print that file's idprint(result.file_id)# print that file's version idprint(result.version_info.id)5. Update File DetailsAccepts all the parameters as per
theAPI documentation here.
The first argument to theupdate_file_details()method is the file ID, and a second argument is an object with the
parameters to be
updated.fromimagekitio.models.UpdateFileRequestOptionsimportUpdateFileRequestOptionsextensions=[{'name':'remove-bg','options':{'add_shadow':True,'bg_color':'red'}},{'name':'google-auto-tagging','minConfidence':80,'maxTags':10}]options=UpdateFileRequestOptions(remove_ai_tags=['remove-ai-tag-1','remove-ai-tag-2'],webhook_url='url',extensions=extensions,tags=['tag-1','tag-2'],custom_coordinates='10,10,100,100',custom_metadata={'test':11},)result=imagekit.update_file_details(file_id='62cfd39819ca454d82a07182',options=options)# required# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print that file's idprint(result.file_id)6. Add tagsAccepts a list offile_idsandtagsas a parameter to be used to add tags. All parameters specified in
theAPI documentation herecan be passed to
the.add_tags()functions to get the results.result=imagekit.add_tags(file_ids=['file-id-1','file-id-2'],tags=['add-tag-1','add-tag-2'])# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# list successfully updated file idsprint(result.successfully_updated_file_ids)# print the first file's idprint(result.successfully_updated_file_ids[0])7. Remove tagsAccepts a list offile_idsandtagsas a parameter to be used to remove tags. All parameters specified in
theAPI documentation herecan be passed to
the.remove_tags()functions to get the results.result=imagekit.remove_tags(file_ids=['file-id-1','file-id-2'],tags=['remove-tag-1','remove-tag-2'])# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# list successfully updated file idsprint(result.successfully_updated_file_ids)# print the first file's idprint(result.successfully_updated_file_ids[0])8. Remove AI tagsAccepts a list offile_idsandai_tagsas a parameter to remove AI tags. All parameters specified in
theAPI documentation herecan be passed to
the.remove_ai_tags()functions to get the results.result=imagekit.remove_ai_tags(file_ids=['file-id-1','file-id-2'],ai_tags=['remove-ai-tag-1','remove-ai-tag-2'])# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# list successfully updated file idsprint(result.successfully_updated_file_ids)# print the first file's idprint(result.successfully_updated_file_ids[0])9. Delete FileDelete a file according to theAPI documentation here. It accepts the file ID of the File that has to be
deleted.file_id="file_id"result=imagekit.delete_file(file_id=file_id)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)10. Delete FileVersionDelete a file version as per
theAPI documentation here.
The method accepts thefile_idand particular version id of the file that has to be deleted.result=imagekit.delete_file_version(file_id="file_id",version_id="version_id")# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)11. Bulk File Delete by IDsDelete a file as per theAPI documentation here.
The method accepts a list of file IDs that have to be deleted.result=imagekit.bulk_file_delete(file_ids=["file_id1","file_id2"])# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# list successfully deleted file idsprint(result.successfully_deleted_file_ids)# print the first file's idprint(result.successfully_deleted_file_ids[0])12. Copy fileCopy a file according to theAPI documentation here.
The method acceptssource_file_path,destination_path, andinclude_file_versionsof the file that has to be copied.fromimagekitio.models.CopyFileRequestOptionsimportCopyFileRequestOptionsoptions=\CopyFileRequestOptions(source_file_path='/source_file_path.jpg',destination_path='/destination_path',include_file_versions=True)result=imagekit.copy_file(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)13. Move FileMove a file as per theAPI documentation here.
The method acceptssource_file_pathanddestination_pathof the file that has to be moved.fromimagekitio.models.MoveFileRequestOptionsimportMoveFileRequestOptionsoptions=\MoveFileRequestOptions(source_file_path='/source_file_path.jpg',destination_path='/destination_path')result=imagekit.move_file(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)14. Rename FileRename a file per theAPI documentation here.
The method accepts thefile_path,new_file_name, andpurge_cacheboolean that has to be renamed.fromimagekitio.models.RenameFileRequestOptionsimportRenameFileRequestOptionsoptions=RenameFileRequestOptions(file_path='/file_path.jpg',new_file_name='new_file_name.jpg',purge_cache=True)result=imagekit.rename_file(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the purge request idprint(result.purge_request_id)15. Restore file VersionRestore a file as per
theAPI documentation here.
The method accepts thefile_idandversion_idof the file that has to be restored.result=imagekit.restore_file_version(file_id="file_id",version_id="version_id")# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print that file's idprint(result.file_id)16. Create FolderCreate a folder per theAPI documentation here.
The method acceptsfolder_nameandparent_folder_pathas options that must be created.fromimagekitio.models.CreateFolderRequestOptionsimportCreateFolderRequestOptionsoptions=CreateFolderRequestOptions(folder_name='test',parent_folder_path='/')result=imagekit.create_folder(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)17. Delete FolderDelete a folder as per theAPI documentation here.
The method acceptsfolder_pathas an option that must be deleted.fromimagekitio.models.DeleteFolderRequestOptionsimportDeleteFolderRequestOptionsoptions=DeleteFolderRequestOptions(folder_path='/test/demo')result=imagekit.delete_folder(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)18. Copy FolderCopy a folder as per theAPI documentation here.
The method accepts thesource_folder_path,destination_path, andinclude_file_versionsboolean as options that
have to be copied.fromimagekitio.models.CopyFolderRequestOptionsimportCopyFolderRequestOptionsoptions=\CopyFolderRequestOptions(source_folder_path='/source_folder_path',destination_path='/destination/path',include_file_versions=True)result=imagekit.copy_folder(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the job's idprint(result.job_id)19. Move FolderMove a folder as per theAPI documentation here.
The method accepts thesource_folder_pathanddestination_pathof a folder as options that must be moved.fromimagekitio.models.MoveFolderRequestOptionsimportMoveFolderRequestOptionsoptions=\MoveFolderRequestOptions(source_folder_path='/source_folder_path',destination_path='/destination_path')result=imagekit.move_folder(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the job's idprint(result.job_id)20. Get Bulk Job StatusAccepts thejob_idto get bulk job status as per
theAPI documentation here.
The method takes only jobId.result=imagekit.get_bulk_job_status(job_id="job_id")# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the job's idprint(result.job_id)# print the statusprint(result.status)21. Purge CacheProgrammatically issue an explicit cache request as per
theAPI documentation here.
Accepts the full URL of the File for which the cache has to be cleared.result=imagekit.purge_file_cache(file_url="full_url_of_file")# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the purge file cache request idprint(result.request_id)22. Purge Cache StatusGet the purge cache request status using thecache_request_idreturned when a purge cache request gets submitted as per theAPI documentation hereresult=imagekit.get_purge_file_cache_status(purge_cache_id="cache_request_id")# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the purge file cache statusprint(result.status)23. Get File MetadataAccepts thefile_idand fetches the metadata as per
theAPI documentation hereresult=imagekit.get_file_metadata(file_id="file_id")# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the file metadata fieldsprint(result.width)print(result.exif.image.x_resolution)24. Get File Metadata from remote URLAccepts theremote_file_urland fetches the metadata as per
theAPI documentation hereresult=imagekit.get_remote_file_url_metadata(remote_file_url="remote_file_url")# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the file metadata fieldsprint(result.width)print(result.exif.image.x_resolution)25. Create CustomMetaDataFieldsAccepts an option specifying the parameters used to create custom metadata fields. All parameters specified in
theAPI documentation herecan be passed as it is with the correct values to get the results.Check for theallowed values in the schema.Example:# Example for the type numberfromimagekitio.models.CreateCustomMetadataFieldsRequestOptionsimportCreateCustomMetadataFieldsRequestOptionsfromimagekitio.models.CustomMetadataFieldsSchemaimportCustomMetadataFieldsSchemafromimagekitio.models.CustomMetaDataTypeEnumimportCustomMetaDataTypeEnumschema=CustomMetadataFieldsSchema(type=CustomMetaDataTypeEnum.Number,min_value=100,max_value=200)options=CreateCustomMetadataFieldsRequestOptions(name='test',label='test',schema=schema)result=imagekit.create_custom_metadata_fields(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the id of created custom metadata fieldsprint(result.id)# print the schema's type of created custom metadata fieldsprint(result.schema.type)# MultiSelect type Examplefromimagekitio.models.CreateCustomMetadataFieldsRequestOptionsimportCreateCustomMetadataFieldsRequestOptionsfromimagekitio.models.CustomMetadataFieldsSchemaimportCustomMetadataFieldsSchemafromimagekitio.models.CustomMetaDataTypeEnumimportCustomMetaDataTypeEnumschema=\CustomMetadataFieldsSchema(type=CustomMetaDataTypeEnum.MultiSelect,is_value_required=True,default_value=['small',30,True],select_options=['small','medium','large',30,40,True,])options=\CreateCustomMetadataFieldsRequestOptions(name='test-MultiSelect',label='test-MultiSelect',schema=schema)result=imagekit.create_custom_metadata_fields(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the name of created custom metadata fieldsprint(result.name)# print the schema's select options of created custom metadata fieldsprint(result.schema.select_options)# Date type Examplefromimagekitio.models.CreateCustomMetadataFieldsRequestOptionsimportCreateCustomMetadataFieldsRequestOptionsfromimagekitio.models.CustomMetadataFieldsSchemaimportCustomMetadataFieldsSchemafromimagekitio.models.CustomMetaDataTypeEnumimportCustomMetaDataTypeEnumschema=CustomMetadataFieldsSchema(type=CustomMetaDataTypeEnum.Date,min_value='2022-11-29T10:11:10+00:00',max_value='2022-11-30T10:11:10+00:00')options=CreateCustomMetadataFieldsRequestOptions(name='test-date',label='test-date',schema=schema)result=imagekit.create_custom_metadata_fields(options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the label of created custom metadata fieldsprint(result.label)# print the schema's min value of created custom metadata fieldsprint(result.schema.min_value)26. Get CustomMetaDataFieldsAccepts theinclude_deletedboolean as the initial parameter and fetches the metadata as per
theAPI documentation here.result=imagekit.get_custom_metadata_fields()# in this case, it will consider includeDeleted as a False# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the first customMetadataField's idprint(result.list[0].id)# print the first customMetadataField schema's typeprint(result.list[0].schema.type)result=imagekit.get_custom_metadata_fields(include_deleted=True)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the first customMetadataField's nameprint(result.list[0].name)# print the first customMetadataField schema's default valueprint(result.list[0].schema.default_value)27. Update CustomMetaDataFieldsAccepts afield_idand options for specifying the parameters to be used to edit custom metadata fields
as per
theAPI documentation here.fromimagekitio.models.CustomMetadataFieldsSchemaimportCustomMetadataFieldsSchemafromimagekitio.models.UpdateCustomMetadataFieldsRequestOptionsimportUpdateCustomMetadataFieldsRequestOptionsschema=CustomMetadataFieldsSchema(min_value=100,max_value=200)options=UpdateCustomMetadataFieldsRequestOptions(label='test-update',schema=schema)result=imagekit.update_custom_metadata_fields(field_id='id_of_custom_metadata_field',options=options)# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)# print the label of updated custom metadata fieldsprint(result.label)# print the schema's min value of updated custom metadata fieldsprint(result.schema.min_value)28. Delete CustomMetaDataFieldsAccepts the id to delete the custom metadata fields as per
theAPI documentation here.result=imagekit.delete_custom_metadata_field(field_id="id_of_custom_metadata_field")# Final Resultprint(result)# Raw Responseprint(result.response_metadata.raw)Utility functionsWe have included the following commonly used utility functions in this package.Authentication parameter generationSuppose one wants to implement client-side file upload. In that case, one will need a token, expiry timestamp, and a valid signature for that upload. The SDK provides a simple method that one can use in their code to generate these authentication parameters.Note: Any client-side code should never expose The Private API Key. One must always generate these authentications parameters on the server-sideauthenticationauthentication_parameters = imagekit.get_authentication_parameters(token, expire)Returns{"token":"unique_token","expire":"valid_expiry_timestamp","signature":"generated_signature"}Both thetokenandexpireparameters are optional. If not specified, the SDK uses the UUID to generate a random token and internally generates a valid expiry timestamp. Thetokenandexpireused to generatesignatureis part of a response returned by the server.Distance calculation between twopHashvaluesPerceptual hashing allows you to construct a has value that uniquely identifies an input image based on the contents
of an image.imagekit.io metadata APIreturns thepHashvalue of an image in the response. You can use this value
tofind a duplicate or similar imageby calculating the distance between the two images.This SDK exposes thephash_distancefunction to calculate the distance between twopHashvalues. It accepts twopHashhexadecimal
strings and returns a numeric value indicative of the difference between the two images.defcalculate_distance():# fetch metadata of two uploaded image files...# extract pHash strings from both: say 'first_hash' and 'second_hash'...# calculate the distance between them:distance=imagekit.phash_distance(first_hash,second_hash)returndistanceDistance calculation examplesimagekit.phash_distance('f06830ca9f1e3e90','f06830ca9f1e3e90')# output: 0 (same image)imagekit.phash_distance('2d5ad3936d2e015b','2d6ed293db36a4fb')# output: 17 (similar images)imagekit.phash_distance('a4a65595ac94518b','7838873e791f8400')# output: 37 (dissimilar images)HTTP response metadata of Internal APIHTTP response metadata of the internal API call can be accessed using the _response_metadata on the Result object.
Example:result=imagekit.upload_file(file="<url|base_64|binary>",file_name="my_file_name.jpg",)# Final Resultprint(result)print(result.response_metadata.raw)print(result.response_metadata.http_status_code)print(result.response_metadata.headers)Sample Code InstructionTo runsamplecode go to the code samples here are hosted on GitHub -https://github.com/imagekit-samples/quickstart/tree/master/pythonand run.pythonsample.pyHandling errorsCatch and respond to invalid data, internal problems, and more.ImageKit Python SDK raises exceptions for many reasons, such as not found, invalid parameters, authentication, and
internal server errors. Therefore, we recommend writing code that gracefully handles all possible API exceptions.Example:fromimagekitio.exceptions.BadRequestExceptionimportBadRequestExceptionfromimagekitio.exceptions.UnauthorizedExceptionimportUnauthorizedExceptionfromimagekitio.exceptions.ForbiddenExceptionimportForbiddenExceptionfromimagekitio.exceptions.TooManyRequestsExceptionimportTooManyRequestsExceptionfromimagekitio.exceptions.InternalServerExceptionimportInternalServerExceptionfromimagekitio.exceptions.PartialSuccessExceptionimportPartialSuccessExceptionfromimagekitio.exceptions.NotFoundExceptionimportNotFoundExceptionfromimagekitio.exceptions.UnknownExceptionimportUnknownExceptiontry:# Use ImageKit's SDK to make requests...print('Run image kit api')exceptBadRequestException,e:# Missing or Invalid parameters were supplied to Imagekit.io's APIprint('Status is: '+e.response_metadata.http_status_code)print('Message is: '+e.message)print('Headers are: '+e.response_metadata.headers)print('Raw body is: '+e.response_metadata.raw)exceptUnauthorizedException,e:print(e)exceptForbiddenException,e:# No valid API key was provided.print(e)exceptTooManyRequestsException,e:# Can be for the following reasons:# ImageKit could not authenticate your account with the keys provided.# An expired key (public or private) was used with the request.# The account is disabled.# If you use the upload API, the total storage limit (or upload limit) is exceeded.print(e)exceptInternalServerException,e:# Too many requests made to the API too quicklyprint(e)exceptPartialSuccessException,e:# Something went wrong with ImageKit.io API.print(e)exceptNotFoundException,e:# Error cases on partial success.print(e)exceptUnknownException,e:# If any of the field or parameter is not found in the dataprint(e)# Something else happened, which can be unrelated to ImageKit; the reason will be indicated in the message fieldDevelopmentTestsTests are powered byTox.$gitclonehttps://github.com/imagekit-developer/imagekit-python&&cdimagekit-python
$pipinstalltox
$toxSampleGet & Install local ImageKit Python SDK$gitclonehttps://github.com/imagekit-developer/imagekit-python&&cdimagekit-python
$pipinstall-e.Get samplesTo integrate ImageKit Samples in the Python, the code samples covered here are hosted on GitHub -https://github.com/imagekit-samples/quickstart/tree/master/python.Open thepython/sample.pyfile and replace placeholder credentials with actual values. You can get the value ofURL-endpointfrom your ImageKit dashboard. API keys can be obtained from thedevelopersection in your ImageKit dashboard.In thepython/sample.pyfile, set the following parameters for authentication:fromimagekitioimportImageKitimagekit=ImageKit(private_key='your private_key',public_key='your public_key',url_endpoint='your url_endpoint')To install dependencies that are in thepython/requirements.txtfile, can fire this command to install them:pipinstall-rpython/requirements.txtNow runpython/sample.py. If you are using CLI Tool (Terminal/Command prompt), open the project in CLI and execute it.# if not installed alreadypipinstallimagekitio# if installing local sdkpipinstall-e<path_to_local_sdk># to run sample.py filepython3python/sample.pySupportFor any feedback or to report any issues or general implementation support, please reach out
tosupport@imagekit.ioLinksDocumentationMain WebsiteLicenseReleased under the MIT license.