REST API
This guide walks you through creating an AI Search instance using the REST API.
You need an API token with AI Search:Edit and AI Search:Run permissions.
-
In the Cloudflare dashboard, go to My Profile > API Tokens.
Go to API Tokens -
Select Create Token.
-
Select Create Custom Token.
-
Enter a Token name, for example
AI Search Manager. -
Under Permissions, add two permissions:
- Account > AI Search:Edit
- Account > AI Search:Run
-
Select Continue to summary, then select Create Token.
-
Copy and save the token value. This is your
API_TOKEN.
Use the Create instance API to create an instance. Replace <ACCOUNT_ID> with your account ID.
curl -X POST "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai-search/instances" \ -H "Authorization: Bearer <API_TOKEN>" \ -H "Content-Type: application/json" \ --data '{ "id": "my-instance" }'You can create an instance that is connected to a website or R2 bucket as a data source. AI Search indexes the content automatically.
Website:
Automatically crawl and index a website that you own.
curl -X POST "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai-search/instances" \ -H "Authorization: Bearer <API_TOKEN>" \ -H "Content-Type: application/json" \ --data '{ "id": "my-instance", "type": "web-crawler", "source": "example.com" }'R2 bucket:
Index documents stored in an R2 bucket. Connecting an R2 bucket requires a service API token. If you have never created an R2-backed instance before, you need to pass the token_id field in the create request. Refer to the service API token configuration for setup instructions.
curl -X POST "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai-search/instances" \ -H "Authorization: Bearer <API_TOKEN>" \ -H "Content-Type: application/json" \ --data '{ "id": "my-instance", "type": "r2", "source": "<R2_BUCKET_NAME>", "token_id": "<SERVICE_TOKEN_ID>" }'If you did not create an instance that is connected to a data source, upload files using the Items API. You can skip this step if you connected a website or R2 bucket.
curl -X POST "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai-search/instances/my-instance/items" \ -H "Authorization: Bearer <API_TOKEN>" \ -F "file=@/path/to/your/file.pdf"AI Search indexes uploaded files automatically.
Check if your content has finished indexing.
curl "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai-search/instances/my-instance/stats" \ -H "Authorization: Bearer <API_TOKEN>"Once indexing is complete, run your first query.
curl "https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/ai-search/instances/my-instance/search" \ -H "Authorization: Bearer <API_TOKEN>" \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "content": "How do I get started?", "role": "user" } ] }'You can also test queries in the dashboard by going to your instance and selecting the Playground tab.