Procedure
Since Dify API extensions require a publicly accessible address as the API Endpoint, the API extension needs to be deployed to a public address. Here we use Cloudflare Workers to deploy the API extension. Clone the Example GitHub Repository. This repository contains a simple API extension that can be modified as a starting point.wrangler.toml file and modify name and compatibility_date to your application name and compatibility date.
The configuration we need to pay attention to here is the TOKEN in vars. When adding an API extension in Dify, we need to fill in this Token. For security reasons, we recommend using a random string as the Token. You should not write the Token directly in the source code, but pass it through environment variables. Therefore, please do not commit wrangler.toml to your code repository.
src/index.ts. This example demonstrates how to interact with third-party APIs.
npm commands to deploy your API extension.
endpoint path. The specific definition of this path can be found in src/index.ts.
Alternatively, you can use the npm run dev command to deploy locally for testing.
About Bearer Auth
hono/bearer-auth package to implement Bearer validation. You can use c.env.TOKEN in src/index.ts to get the Token.
About Parameter Validation
zod to define parameter types here. You can use zValidator in src/index.ts to validate parameters. Use const { point, params } = c.req.valid("json"); to get the validated parameters.
The point here has only two values, so we use z.union to define it. params is an optional parameter, so we use z.optional to define it. There will be an inputs parameter, which is a Record<string, any> type. This type represents an object with string keys and any values. This type can represent any object. You can use params?.inputs?.count in src/index.ts to get the count parameter.
Get Cloudflare Workers Logs
Reference: