HTTP Responses - Webhooks

HTTP Responses / Webhooks

On this page:

Webhooks (also called "HTTP Callbacks" or "HTTP Push") are a way of sending real-time HTTP notifications to the endpoints you provide. The Optidash API offers a robust webhook delivery system you can leverage right away.

When using Webhooks as your response method of choice, the API will immediately return a unique request id with status code 202 Accepted for every call. Once the processing of your request on our backend is complete (usually within 100ms), the API will POST a full JSON response to the Webhook endpoint you provided in your request. That notification will also include the same id parameter you received with your initial API call so you can easily pair your requests with Webhook notifications.

Configuring Webhook Delivery

To use Webhooks as a response method, the JSON request must include a webhook hash with a mandatory url parameter. That URL will be used as a Webhook endpoint and will instruct the API to send a full JSON response to that URL. Optionally you may also include a delay parameter which takes an integer between 1 - 604800 and sets the number of seconds after which the notification will be sent. By default, delay is set to 0 meaning the Webhook will be delivered immediately after the processing is finished.

Endpoints can use HTTP Basic Auth and include query strings. You may encode those as part of the endpoint URL: https://user:pass@www.website.com/endpoint?query=opti
webhook hash attributes:
AttributeTypeRequiredDescription
urlStringYesA valid endpoint URL as described in RFC 3986.
delayIntegerNoDelay in seconds within 1 - 604800 range (maximum one week) after which the notification will be sent. Defaults to 0.
{
    "webhook": {
        "url": "https://www.website.com/endpoint",
        "delay": 60
    }
}

Example Webhook Flow

Let's take a look at an example flow when using Webhooks. We'll use the Image Fetch method (provide an image URL) and resize that image to 100x75 pixels. First we make a standard request to the API and include our webhook hash:

curl https://api.optidash.ai/1.0/fetch -X POST -u your-api-key: \
-H "Content-Type: application/json" \
-d '{
    "url": "https://www.website.com/image.jpg",
    "resize": {
        "width": 100,
        "height": 75
    },
    "webhook": {
        "url": "https://www.website.com/endpoint"
    }
}'

The API immediately responds with 202 Accepted and sends a request id in the response JSON:

HTTP/1.1 202 ACCEPTED

Date: [[now]]
Status: 202 ACCEPTED
Content-Type: application/json

{
    "success": true,
    "code": 202,
    "id": "f26656d4-3322-4279-acf4-0e1b3ef9d4bd"
}

After the processing is finished the API delivers a POST notification to your endpoint with full JSON metadata. Please make sure that the id property in the notification matches the initial request id you received when calling the API.

{
    "success": true,
    "code": 200,
    "id": "f26656d4-3322-4279-acf4-0e1b3ef9d4bd",
    "input": {
        ...
    },
    "output": {
        ...
    }
}

Receiving a Webhook Notification

Your endpoints must respond to a Webhook notification within 10 seconds with a 200 OK status code. Responses that take longer than 10 seconds will be treated as a failure. All response codes outside of 2xx range, including 3xx codes, will also indicate that you did not receive the webhook. That means that a URL redirection or a "Not Modified" response will be treated as a failure.

Webhooks will come from the following IP address range: 212.224.84.128/26. You may refuse other IP addresses from your endpoint configuration.

Cross Site Request Forgery (CSRF)

Many applications use CSRF protection as an important security measure to prevent cross-site request forgery attempts. Unfortunately that mechanism will also prevent Optidash Webhooks from hitting your endpoints. You must disable forgery protection for the routes you set up to listen for events from Optidash.

Querying Delivered Webhooks

We keep the history of delivered webhooks for 60 days. If you'd like to programmatically query a Webhook status and payload, please consult the Querying Webhooks section of this documentation.

Code Examples for Webhooks

Below, you'll find examples of how to use Webhooks from the Optidash API:

  • PHP
  • Node
  • Ruby
  • Go
  • Python
  • Java
<?php

/**
* Instantiate new `$opti` by calling a constructor
*/

$opti = new Optidash\Optidash('your-api-key');


/**
* Provide a publicly available image URL with fetch(string) method,
* resize the image to 100 x 75 and set a Webhook as a response delivery mode
*/

$opti
    ->fetch('https://www.website.com/image.jpg')
    ->resize(array(
        'width' => 100,
        'height' => 75
    ))
    ->webhook(array(
        'url' => 'https://www.website.com/endpoint'
    ))
    ->toJSON(function ($error, $meta) {
        if (!empty($error)) {
            throw new Exception($error);
        }

        /**
        * You'll find your unique request ID within the `$meta` variable, for example:
        *
        * [
        *     'success' => true,
        *     'code' => 202,
        *     'id' => 'f26656d4-3322-4279-acf4-0e1b3ef9d4bd'
        * ]
        *
        * Remember to always check if the `success` property is set to `true`.
        */

        if ($meta['success'] == true) {
            print ($meta['id']);
        } else {
            print ($meta['message']);
        }
    });
/**
* Module dependencies
*/

const Optidash = require("optidash");


/**
* Instantiate new `opti` by calling a constructor
*/

const opti = new Optidash("your-api-key");


/**
* Provide a publicly available image URL with fetch(string) method,
* resize the image to 100 x 75 and set a Webhook as a response delivery mode
*/

opti
    .fetch("https://www.website.com/image.jpg")
    .resize({
        width: 100,
        height: 75
    })
    .webhook({
        url: "https://www.website.com/endpoint"
    })
    .toJSON((err, meta) => {
        if (err) {
            return console.log(err);
        }

        /**
        * You'll find your unique request ID within the `meta` variable, for example:
        *
        * {
        *     "success": true,
        *     "code": 202,
        *     "id": "f26656d4-3322-4279-acf4-0e1b3ef9d4bd"
        * }
        *
        * Remember to always check if the `success` property is set to `true`.
        */

        if (meta.success) {
            console.log(meta.id);
        } else {
            console.log(meta.message);
        }
    });
##
# Require dependencies

require "optidash"


##
# Instantiate new `opti` by calling a constructor

opti = Optidash.new("your-api-key")


##
# Provide a publicly available image URL with fetch(string) method,
# resize the image to 100 x 75 and set a Webhook as a response delivery mode

err, meta = opti
    .fetch("https://www.website.com/image.jpg")
    .resize(
        width: 100,
        height: 75
    )
    .webhook(
        url: "https://www.website.com/endpoint"
    )
    .to_json

abort(err) if err


##
# You'll find your unique request ID within the `meta` variable, for example:
#
# {
#     "success": true,
#     "code": 202,
#     "id": "f26656d4-3322-4279-acf4-0e1b3ef9d4bd"
# }
#
# Remember to always check if the `success` property is set to `true`.

if meta["success"]
    puts meta["id"]
else
    puts meta["message"]
end
package main

import (
    "fmt"
    "github.com/optidash/optidash-go"
)

func main() {

    /**
    * Instantiate new `opti` by calling a constructor
    */

    opti, err := optidash.NewClient("your-api-key")

    if err != nil {
        panic(err)
    }


    /**
    * Provide a publicly available image URL with Fetch(string) method,
    * resize the image to 100 x 75 and set a Webhook as a response delivery mode
    */

    meta, err := opti.
        Fetch("https://www.website.com/image.jpg").
        Resize(optidash.P{
            "width": 100,
            "height": 75
        }).
        Webhook(optidash.P{
            "url": "https://www.website.com/endpoint",
        }).
        ToJSON()

    if err != nil {
        panic(err)
    }


    /**
    * You'll find your unique request ID within the `meta` variable, for example:
    *
    * {
    *     "success": true,
    *     "code": 202,
    *     "id": "f26656d4-3322-4279-acf4-0e1b3ef9d4bd"
    * }
    *
    * Remember to always check if the `success` property is set to `true`.
    */

    if meta["success"].(map[string]interface{})["success"].(bool) {
        fmt.Println(meta["id"])
    } else {
        fmt.Println(meta["message"])
    }
}
##
# Import dependencies

from optidash import optidash


##
# Instantiate new `opti` by calling a constructor

opti = optidash('your-api-key')


##
# Provide a publicly available image URL with fetch(string) method,
# resize the image to 100 x 75 and set a Webhook as a response delivery mode

err, meta = (
    opti
        .fetch('https://www.website.com/image.jpg')
        .resize({
            'width': 100,
            'height': 75
        })
        .webhook({
            'url': 'https://www.website.com/endpoint'
        })
        .toJSON()
)

if err is not None:
    raise StandardError(err)


##
# You'll find your unique request ID within the `meta` variable, for example:
#
# {
#     "success": true,
#     "code": 202,
#     "id": "f26656d4-3322-4279-acf4-0e1b3ef9d4bd"
# }
#
# Remember to always check if the `success` property is set to `true`.

if meta['success'] is True:
    print (meta['id'])
else:
    print (meta['message'])
package com.optidash.examples;

/**
* Import dependencies
*/

import static com.optidash.OperationConfiguration.settings;
import com.optidash.Optidash;
import com.optidash.Fetch;
import com.optidash.Response;

public class Webhooks {
    public static void main(String[] args) {

        /**
        * Instantiate new `opti` by calling a constructor
        */

        Optidash opti = new Optidash("your-api-key");

        /**
        * Provide a publicly available image URL with fetch(string) method,
        * resize the image to 100 x 75 and set a Webhook as a response delivery mode
        */

        final Fetch fetch = opti.fetch("https://www.website.com/image.jpg");

        fetch.resize(
            settings()
                .set("width", 100)
                .set("height", 75)
        );

        fetch.webhook(
            settings()
                .set("url", "https://www.website.com/endpoint")
        );

        final Response response = fetch.toJson();

        /**
        * You'll find your unique request ID within the `Response#getMetadata()` property, for example:
        *
        * {
        *     "success": true,
        *     "code": 202,
        *     "id": "f26656d4-3322-4279-acf4-0e1b3ef9d4bd"
        * }
        *
        * Remember to always check if the `Response#successful` property is set to `true`.
        */

        if (response.isSuccessful()) {
            System.out.println(response.getMetadata().get("id"));
        } else {
            System.out.println(response.getMessage());
        }
    }
}
Grace Przemek Magda Damian
Have questions? Let's talk!We usually respond in just under an hour

Thanks for reaching out!

We've received your message
and will get to it as quickly as possible.

Whoops, looks like something went wrong.

We encountered an unexpected error and cannot complete your request. Please try reloading the page.