Cloudinary Blog

A Blueprint for AWS-Secured Webhook Listeners for Cloudinary

By
A Blueprint for AWS-Secured Webhook Listeners for Cloudinary

tl;dr: An AWS-secured and optimized Cloudinary webhook listener for extending the Cloudinary service

Code: Github


A webhook is a communication medium for sending notifications from one platform to another about events that occurred. In place are user-defined HTTP callbacks that are triggered by specific events. When a triggered event takes place on the source site, the webhook listens to the event, collects the data, and sends it to the URL you specified in the form of an HTTP request.

With Cloudinary webhooks, you can augment Cloudinary capabilities with home-grown code or third-party APIs by triggering actions in your application when certain events occur in your Cloudinary account. In essence, a Cloudinary webhook is a small piece of code that takes action upon a Cloudinary event, such as a file upload, a metadata modification, or the complete processing of a media asset.

The sections below describe a blueprint of a Hello World! Cloudinary webhook listener that is deploy-ready and customizable with a few clicks or lines of code.

Real-Life Use Case

A prominent digital-transformation agency that specializes in luxury fashion migrated a legacy DAM to Cloudinary to leverage our platform’s new capabilities but continue to use the current middleware. Here’s what the agency aimed to accomplish:

Accordingly, the agency did the following:

  1. Adopted the template in this post to quickly deploy a global web listener that checks if an asset or the nominated metadata has been changed and, if so, update another metadata field to reflect the last update timestamp (last_update_timestamp).

  2. Fulfilled the polling requirement with Cloudinary’s search API.

  3. Through the same web listener, determined if an event is an upload of a video. If so, gauge if the video size is large or small.

  4. Executed the required preprocessing with Cloudinary’s explicit method.

Vincenzo Cerbone, technical consultant of openmind, said:

“We had a previous experience in batch synchronization with a legacy DAM based on polling techniques. Despite the pros and cons of that approach, we valued the user's asset state on Cloudinary the most. That means that we let the CMS act more as a ‘slave’ of the user's decisions on the Cloudinary side rather than the opposite. The connection point between the two worlds is the mandatory CMS_ID SMD custom field. The rest of the ‘magic’ is done through AWS Lambda functions (WebListeners) Yuval suggested. Ultimately, that mechanism took care of all the essential transformations.

We look forward to other upcoming features from Cloudinary that this use case can take advantage of. It’s truly exciting to be part of this process!”

Use Cases

Cloudinary offers an end-to-end media-management solution for images and videos, including upload, storage, administration, transformation, optimization, and delivery. The many features open up numerous use cases for a webhook listener, such as the following:

  • Updates to an activity feed on a front-end system with asset-related events and details, such as when someone uploads an asset to the Cloudinary Media Library or deletes one from there.
  • Bulk processing of records listed in an uploaded CSV file.
  • Updates to the asset metadata stored in an external database in the event of updates to an asset’s metadata in the Cloudinary Media Library
  • Extraction of metadata from assets uploaded with Cloudinary’s upload widget—for tagging in an external system.
  • Dispatch of a text message or email to a customer in case of asset uploads.

Overview Diagram

Prerequisites

To create a blueprint for a Cloudinary webhook listener, you need the following:

Installation and Setup

Upon installation, the blueprint for a Cloudinary webhook listener calls for the following:

  1. Install a Lambda listener that adds the tag Hello World! to any asset you upload to your Cloudinary account.
  2. Store your Cloudinary account’s credentials in the Amazon Web Services (AWS) Secrets Manager, logging the web-listener activity in Cloudwatch.

The installation and setup process takes a few minutes. The boilerplate code is under 50 lines of Python script, easily accessible through AWS Lambda’s code editor.

To set up the tutorial, follow the instructions in the README.md file.

Code Tutorial

  1. Write to your preferred logging solution: either use the default AWS logger with CloudWatch or override set_logger. The entry point is where the Cloudinary event was first received.

    validate_signature ensures that the events received are authentic. Note the mandatory return syntax, which informs Cloudinary that the function has been completed successfully. If the function fails, Cloudinary resends the notification three more times: once after three minutes, then after nine minutes, and then after 27 minutes. exception_wrapper adheres to that syntax as well.

  2. Place your code in the main_process function. The example below shows how to write back a tag to the uploaded asset. Here, to avoid additional I/O operations, the utility function config_cloudinary_instance() validates the event's authenticity with cached credentials.

Copy to clipboard
def lambda_handler(event, context):
    try:
        set_logger()
        logger.info(json.dumps(event))
        validate_signature(event)
        main_process(json.loads(event['body']))
    except Exception as e:
        return exception_wrapper(logger, e)
    return {'statusCode': 200, 'body': 'OK', 'isBase64Encoded': False}

The main_process function is where you’ll place your own code. The example shows how to write back a tag to the uploaded asset. To prevent additional I/O operations, the utility function config_cloudinary_instance() ensures that the cached credentials that validated the event's authenticity are in use.

Further Options and Resources

Check out the resources below on creating and managing webhook listeners.

When uploading assets:

When delivering assets:

Summary

As always, our goal at Cloudinary is to efficiently manage, transform, and optimize your web and mobile app's media assets, freeing you up to focus on your core business logic. Oftentimes, real-world use cases are complex and diverse, involving front-end and back-end systems as well as asynchronous workflows. Cloudinary’s webhooks with their ability to perform custom computing tasks promise to be useful tools for handling even the most demanding media-management tasks.

We’d much appreciate your feedback on this new blueprint.

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more