Cloudinary Blog

A Blueprint for AWS-Secured Webhook Listeners for Cloudinary

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.

Note
Here‘s [the code for this tutorial](https://github.com/cloudinary-devs/web-listener-blueprint-aws](https://github.com/cloudinary-devs/web-listener-blueprint-aws)

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

Create Lightweight Sites With Low-Code and No-Code Technology

Consumers expect modern websites to be mainly visual. But, the more compelling and complex the related media is, the more data is involved, compounding the site’s weight. In today’s content-craving world, delivering unoptimized media can cost you because it leads to sluggish page loads, resulting in visitors abandoning your site in search of a faster alternative. In fact, a page load that takes more than three seconds can cause as many as 40% of your visitors to bounce. Given this competitive, digital-first environment, you can’t afford to lose page views, for time is of the essence.

Read more
New Accessibility Features for Cloudinary’s Product Gallery Widget

Cloudinary’s Product Gallery widget, which launched in 2019, has enabled many brands to effectively and efficiently showcase their products in a sleek and captivating manner, saving countless hours of development time and accelerating release cycles. By adding Cloudinary’s Product Gallery widget with its customizable UI to their product page, retailers reap numerous benefits, often turning visitors into customers in short order.

Read more
Why Successful Businesses Engage With and Convert Audiences With Visual Media

Most business buyers prefer to research purchase options online, as do many shoppers. No wonder online retail sales in the U.S. rose by 32.4% in 2020—an impressive gain of $105 billion.

For B2B and B2C businesses, text-heavy websites are no longer adequate in attracting shoppers. Instead, engaging visual media—spin images, videos, 3D models, augmented reality—are becoming a must for conveying eye-catching details and differentiators about products or services.

Read more
Making User-Generated Content (UGC) Shoppable With Cloudinary

User-generated content (UGC) is a powerful marketing tool. Not only does video complement marketing efforts for e-commerce by enabling customers to explore products in greater detail, but UGC also adds an element of trust. As a bonus, user-generated video is an exceptional opportunity for e-businesses to attract website traffic without their marketing team having to create promotional videos from scratch. User-generated content drives conversions and brand loyalty as a direct result of authentic interaction.

Read more
Cloudinary Joins The MACH Alliance

As expectations of websites and apps continue to grow, there is more pressure on brands to deliver new and innovative ways to reimagine their digital experience.

The challenge is many companies lack the systems and platforms to stay competitive in this digital revolution and keep up with modern technology. To stay one step ahead, brands have to continuously evolve their martech stack. However this is easier said than done. As marketing, developer, and creative teams look for new solutions they often end up down a rabbit hole. What starts off as an exciting investment to embrace a new technology, system or platform ends up turning into a complicated process and once the dust settles, teams often realize the limiting capabilities of investing in a single vendor.

Read more