Deploy API Tools with Cloudflare Workers
Getting Started
Since the Dify API Extension requires a publicly accessible internet address as an API Endpoint, we need to deploy our API extension to a public internet address. Here, we use Cloudflare Workers for deploying our API extension.
We clone the Example GitHub Repository, which contains a simple API extension. We can modify this as a base.
Open the wrangler.toml
file, and modify name
and compatibility_date
to your application's name and compatibility date.
An important configuration here is the TOKEN
in vars
, which you will need to provide when adding the API extension in Dify. For security reasons, it's recommended to use a random string as the Token. You should not write the Token directly in the source code but pass it via environment variables. Thus, do not commit your wrangler.toml to your code repository.
This API extension returns a random Breaking Bad quote. You can modify the logic of this API extension in src/index.ts
. This example shows how to interact with a third-party API.
This repository simplifies all configurations except for business logic. You can directly use npm
commands to deploy your API extension.
After successful deployment, you will get a public internet address, which you can add in Dify as an API Endpoint. Please note not to miss the endpoint
path.
Other Logic TL;DR
About Bearer Auth
Our Bearer authentication logic is as shown above. We use the hono/bearer-auth
package for Bearer authentication. You can use c.env.TOKEN
in src/index.ts
to get the Token.
About Parameter Validation
We use zod
to define the types of parameters. You can use zValidator
in src/index.ts
for parameter validation. Get validated parameters through const { point, params } = c.req.valid("json");
. Our point has only two values, so we use z.union
for definition. params
is an optional parameter, defined with z.optional
. It includes a inputs
parameter, a Record<string, any>
type representing an object with string keys and any values. This type can represent any object. You can get the count
parameter in src/index.ts
using params?.inputs?.count
.
Accessing Logs of Cloudflare Workers
Reference Content
Last updated