Configure via API
You can create Snippets using the Cloudflare API.
The API token used in API requests to manage Snippets must have at least the following permission:
- Zone > Snippets > Edit
To obtain the complete endpoint, append the Snippets endpoints listed below to the Cloudflare API base URL:
The {zone_id}
argument is the zone ID (a hexadecimal string). You can find this value in the Cloudflare dashboard.
The following table summarizes the available operations.
Operation | Verb + Endpoint |
---|---|
List all code snippets | GET /zones/{zone_id}/snippets |
Create/update code snippet | PUT /zones/{zone_id}/snippets/{snippet_name} |
Delete code snippet | DELETE /zones/{zone_id}/snippets/{snippet_name} |
List snippet rules | GET /zones/{zone_id}/snippets/snippet_rules |
Create/update/delete snippet rules | PUT /zones/{zone_id}/snippets/snippet_rules |
To create or update a Snippet, use the following PUT
request. The snippet is named {snippet_name}
and the body contains the JavaScript code.
The required body parameters are:
files
: The file with your JavaScript code.metadata
: Object containingmain_module
, which must match the filename of the uploaded file.
To make this example work, save your JavaScript code in a file named example.js
, and then execute curl
command with a PUT
request from the folder where example.js
is located.
Once you have created a code snippet, you can link it to rules. This is done via the following PUT
request to the snippet_rules
endpoint.