RatelimitExceeded
: the rate limit has been exceeded for a specific keyOrgRateLimitExceeded
: the rate limit has been exceeded for a specific organizationRateLimitSmoothingUp
: the intermediate rate limit allowance has been increased for a specific keyRateLimitSmoothingDown
: the intermediate rate limit allowance has been decreased for a specific keyQuotaExceeded
: the quota for a specific key has been exceededOrgQuotaExceeded
: the quota for a specific organization has been exceededAuthFailure
: a key has failed authentication or has attempted access and was deniedKeyExpired
: an attempt has been made to access an API using an expired keyVersionFailure
: a key has attempted access to a version of an API that it does not have permission to accessBreakerTripped
: a circuit breaker on a path has tripped and been taken offlineBreakerReset
: a circuit breaker has reset and the path is available againBreakerTriggered
: a circuit breaker has changed state, this is generated when either a BreakerTripped
, or a BreakerReset
event occurs; a status code in the metadata passed to the webhook will indicate which of these events was triggeredHostDown
: the uptime checker has found that a host is down/not availableHostUp
: the uptime checker has found that a host is available again after being offlineTokenCreated
: a token has been createdTokenUpdated
: a token has been changed/updatedTokenDeleted
: a token has been deletedMessage
(string): a human readable message from Tyk Gateway that adds detail about the event
Path
(string): the path of the API endpoint request that led to the event being fired
Origin
(string): origin data for the source of the request (if this exists)
Key
(string): the key that was used in the request
OriginatingRequest
(string): Based64-encoded raw inbound request
BreakerTripped
, BreakerReset
or BreakerTriggered
events are generated.OriginatingRequest
metadata is a Base64-encoded wire-protocol representation of the original request to the event handler. If you are running a service bus or queue that stores failed, throttled or other types of requests, you can decode this object and parse it in order to re-create the original intent of the request (e.g. for post-processing).
event_handlers
section of the API definition.
The handler_name
for the logging event handler should be set to: eh_log_handler
.
The handler_meta
for the logging event handler contains a single field:
prefix
is a label that will be prepended to each log entryAuthFailure
and KeyExpired
events you might add the following to your API definition:
AuthFailure
event will trigger the event handler to generate a log with the prefix AuthFailureEvent
KeyExpired
event will trigger the event handler to generate a log with the prefix KeyExpiredEvent
RatelimitExceeded
event will be fired. A webhook event handler can be employed to notify an upstream system to take actions such as updating a dashboard, notifying the account manager, or adjusting the client’s service tier.
KeyExpired
event will be fired. A webhook event handler can be employed to notify an upstream system to take actions such as renewing the key, logging the failure in a CRM or notifying the account manager to initiate customer communication.
BreakerTripped
event will be fired. A webhook event handler can be employed to update monitoring dashboards or to trigger automated recovery scripts or processes.
AuthFailure
event will fire on the same endpoint more than once if the requesting client is automated. If this event triggered a webhook that caused an email to be sent, then if this event occurred 10 times a second, the email recipient would be flooded with emails. In an attempt to mitigate against events such as this, you can set a cooldown timer, in the webhook handler. This prevents the webhook from being triggered again if the event is fired again within the time period specified.
POST
, the event handler will process a Go template to produce the payload.
If no template is provided in the webhook event handler configuration in the API definition, Tyk Gateway will look for the default file templates/default_webhook.json
. Any text file accessible to the Gateway can be used to store the Go template to be used by the event handler when constructing the payload.
The event handler has access to the event metadata and this can be accessed by the template using the {{.Meta.XXX}}
namespace.
The event type that triggered the event handler can be accessed as {{.Type}}
.
For most event types, the default webhook template has this form:
eventHandlers
object to the server
section of the Tyk OAS Extension (x-tyk-api-gateway
) in your Tyk OAS API Definition.
The eventHandlers
object is an array containing configurations for all event handlers registered with the API.
eventHandlers
object has the following configuration which fully declares the webhook behaviour:
enabled
: enable the event handlertrigger
: the API event that will trigger the webhooktype
: the type of event handler, in this case should be set to webhook
cooldownPeriod
: the webhook cooldown for duplicate events (in duration format, e.g. 10s, 1m30s); use this to prevent flooding of the target endpoint when multiple events are fired in quick successionname
: a human readable name for the webhook, which will be displayed in Tyk Dashboardurl
: this is an absolute URL to which the request will be sentmethod
: this can be any of GET
, PUT
, POST
, PATCH
or DELETE
and will be the HTTP method used to send the request; methods that do not support an encoded request body will not have the event metadata provided with the request; we advise using POST
where possiblebodyTemplate
: this is the path to the webhook template that will be used to construct the request bodyheaders
: a map of custom headers to be provided with the requestRatelimitExceeded
event is fired. The request rate limit has been set at 2 requests per 10 seconds, so simply make three requests in quick succession to trigger the webhook.
The configuration above is a complete and valid Tyk OAS API Definition that you can import into Tyk to try out the local webhook feature.
Note that to test this you will need to provide a valid target URL for your webhook to send the request; we’ve used http://webhook.site
.
eventHandlers
object has the following configuration, which references the externally declared webhook using its id
:
enabled
: enable the event handlertrigger
: the API event that will trigger the webhooktype
: the type of event handler, in this case should be set to webhook
cooldownPeriod
: the webhook cooldown for duplicate events (in duration format, e.g. 10s, 1m30s); use this to prevent flooding of the target endpoint when multiple events are fired in quick successionid
: the webhook id assigned by Tyk to the global webhook when it was created (this can be determined using the list webhooks endpoint in the Tyk Dashboard API)RatelimitExceeded
event is fired. The request rate limit has been set at 2 requests per 10 seconds, so simply make three requests in quick succession to trigger the webhook.
The configuration above is a complete and valid Tyk OAS API Definition that you can import into Tyk to try out the global webhook feature.
Note, however, that to test this you will need to create a global webhook in your Tyk Dashboard and replace the value in id
with the webhook id that Tyk Dashboard has allocated to your webhook. You can find this by querying the list webhooks endpoint in the Tyk Dashboard API.
url
, method
, bodyTemplate
, headers
) within the API definition. This is so that Tyk Gateway knows how to handle the event, as it does not have access to the store of global webhooks registered with Tyk Dashboard.event_handlers.events
section of the
API definition for the appropriate API event.
The event handler object has the following configuration:
handler_name
: this identifies the type of event handler and must be set to eh_web_hook_handler
handler_meta
: this structure configures the HTTP request that will be sent when the webhook is triggeredhandler_meta
object has the following configuration:
method
: this can be any of GET
, PUT
, POST
, PATCH
or DELETE
and will be the HTTP method used to send the
request; methods that do not support an encoded request body will not have the event metadata provided with the
request; we advise using POST
where possibletarget_path
: this is an absolute URL to which the request will be senttemplate_path
: this is the path to the webhook
template that will be
used to construct the request bodyheader_map
: a map of custom headers to be provided with the requestevent_timeout
: the webhook
cooldown for duplicate
events (in seconds); use this to prevent flooding of the target endpoint when multiple events are fired in quick successionAuthFailure
event is fired, the webhook event handler will send a request to
POST http://posttestserver.com/post.php?dir=tyk-event-test
and then start a 10 second cooldown before another webhook
request can be sent.
The request will have one custom header X-Tyk-Test-Header: Tyk v1.BANANA
and the body will be constructed from the
webhook template located at templates/default_webhook.json
.
event_handlers
field
in ApiDefinition Custom Resource Definition (CRD) enables webhooks to be triggered by specific
API events.
The process for configuring webhook event handlers using Tyk Operator is similar to that explained in
Set up a webhook event handler in the Tyk Classic API Definition.
The example API Definition below enables the event handler by setting spec.event_handlers
.
event_handlers
section of the API definition.
The handler_name
for the logging event handler should be set to: eh_log_handler
.
The handler_meta
for the logging event handler contains a single field:
prefix
is a label that will be prepended to each log entryAuthFailure
and KeyExpired
events you might add the following to your API definition:
AuthFailure
event will trigger the event handler to generate a log with the prefix AuthFailureEvent
KeyExpired
event will trigger the event handler to generate a log with the prefix KeyExpiredEvent
event
and context
) and has no return value.
Creating an event handler is very similar to creating custom JS plugins, simply invoke the correct constructors with a closure in the TykJS namespace:
event
objectcontext
Variablecontext
object into your event handler giving access to more information about the request. This object has the following structure:
event
metadata to interact with the Tyk REST API functions, for example:
event_handlers
section of the API definition.
The handler_name
for a custom event handler should be set to: eh_dynamic_handler
.
The handler_meta
for a custom event handler consists of two fields:
name
is the unique name of your middleware objectpath
is the relative path to the file (it can be absolute)sessionHandler
to be invoked in response to the KeyExpired
event you would add the following to your API definition:
monitor
section to your Tyk Gateway configuration file (tyk.conf
).
This has the following fields:
enable_trigger_monitors
: set to true
to have the monitors start to measure quota thresholdsconfiguration
: a webhook configuration objectglobal_trigger_limit
: this is a percentage of the quota that the key must consume for the webhook to be firedmonitor_user_keys
: set to true
to monitor individual tokens (this may result in a large number of triggers as it scales with the number of user tokens that are issued)monitor_org_keys
: set to true
to monitor organization quotasPOST http://posttestserver.com/post.php?dir=tyk-monitor-drop
when 80% of the API-level quota has been consumed. This request will have the x-tyk-monitor-secret
header (set to a value of 12345
) and will provide the content of the template file found at templates/monitor_template.json
in the request body. A minimum of 10 seconds will elapse between successive monitor webhooks being fired.
monitor
section to the access key (Session Object). This has one field, which is an array of trigger_limits
(thresholds) that must be in descending order and represent the percentage of the quota that must be reached in order for the trigger to be fired, for example:
monitor
section to the organization session object.
trigger_limit
will indicate which threshold has been reached (as defined in the session object’s monitor
section).org
will contain the OrgID for the user or organization that triggered the eventkey
will contain the raw API key used in the request only if the event was triggered by a user quotakey
will be blank.
templates/error.json
).
As of v2.3 it is possible to use different templates for specific HTTP error codes
. The content-type
header of the request is also checked, enabling the usage of different template formats, e.g. an XML template.
Please note that it is not possible to override the default message for HTTP 404 errors. These errors indicate that the requested resource could not be found (e.g. the requested URL does not exist).
templates/error_500.json
exists, this template will be used.templates/error.json
.templates/error_500.xml
exists, this template will be used.templates/error.xml
will be used.error.xml
doesn’t exist, templates/error.json
will be used.X-Generator: tyk.io
Please note that for 404 Not found
errors, Tyk will not return this header from a security perspective. To mitigate this issue, in case you want to better understand your clients and provide you, the manager of the platform, with error information, you can set track_404_logs
to true
in your tyk.conf
which will then produce error logs showing the resources that were requested and not found.
If you don’t want to return our default X-Generator header (set to tyk.io) in your templates, set hide_generator_header
to true
in your tyk.conf
file