Dify API Guide 2026: Auth, Endpoints, Python and curl
Every published Dify app can expose a Service API, but the route and response mode depend on the app type. This guide shows how to keep keys on your backend, choose the correct endpoint, make curl and Python requests, and handle streaming responses.
What is the Dify API?
A published Dify app exposes a Service API that your backend can call over HTTPS. The route depends on the published app type: chat apps use the Chat Messages API, workflows use the Workflow Runs API, and text generators use the Completion Messages API. Each request uses an app-scoped API key and a stable user value chosen by your application.
The Dify Cloud base URL is https://api.dify.ai/v1. For a self-hosted deployment, use that instance's own API base URL. Keep the API key on your server. Do not put it in browser JavaScript, a mobile app, a public repository, or any other client that an end user can inspect.
Common use cases
Website chatbot
Embed AI chat into any site without using the Dify widget.
Document automation
Send PDFs or text to a Dify workflow and get structured output back.
SaaS AI features
Add AI writing, summarization, or Q&A to your existing product.
Backend pipelines
Trigger Dify agents from cron jobs, webhooks, or queue processors.
Mobile app backends
Call Dify from your server and return only the data the mobile client needs.
No-code tools
Connect Dify to n8n, Make, or Zapier via HTTP request nodes.
/chat-messages, which is used by Chatflow, Chatbot and Legacy Agent apps. Current Agent apps support streaming only. Workflows and Text Generator apps use different routes.
Getting Your API Key
Create an API key from inside the published Dify app you want to call. An app key is scoped to that app. Use a separate, stable user value to distinguish each end user in your own system.
Open the published app in Dify Studio
Use Dify Cloud or your self-hosted console and open the app your backend will call.
Open the app's API access area
The API reference shown inside the app reflects that app's available Service API routes.
Create an app API key
Use a clear operational name and store the key in your server-side secret manager or environment.
Send it as a Bearer token
Every request needs Authorization: Bearer YOUR_API_KEY.
Test the app identity first
Call GET /info before sending a message. It confirms that the key works and shows the app type.
Choose the Route for Your App Type
Use the route for the app type returned by GET /info. A 400 not_chat_app response usually means the API key belongs to an app that does not match the route.
| Published app type | Primary route | Response modes |
|---|---|---|
| Chatflow, Chatbot, Legacy Agent | POST /chat-messages | Blocking or streaming |
| Agent | POST /chat-messages | Streaming only |
| Workflow | POST /workflows/run | Blocking or streaming |
| Text Generator | POST /completion-messages | Blocking or streaming |
API Endpoints Overview
The Dify API provides endpoints for sending messages, managing conversations, uploading files, and more. All endpoints are relative to the base URL https://api.dify.ai/v1.
| Method | Endpoint | Description |
|---|---|---|
| POST | /chat-messages | Send a message to a Chatflow, Agent, Chatbot or Legacy Agent app. Current Agent apps support streaming only. |
| POST | /completion-messages | Send input to a Text Generator app. Supports blocking and streaming responses. |
| POST | /workflows/run | Run the published version of a Workflow app. Supports blocking and streaming responses. |
| POST | /files/upload | Upload one file for the current end user, then pass the returned ID in a message. Knowledge-base ingestion uses separate Knowledge API routes. |
| GET | /conversations | List all conversations for a user. Use the user parameter to scope results. |
| GET | /messages | List message history for a conversation and stable end-user value. |
| DELETE | /conversations/:id | Delete a conversation for the same end-user value. |
| POST | /messages/:id/feedbacks | Submit a thumbs-up or thumbs-down rating for a specific message. |
| GET | /parameters | Read the published app's input form and feature configuration. |
Your First API Call
These examples call a published chat app. Set DIFY_API_KEY on your server and use a stable, non-sensitive identifier for user. Omit conversation_id or send an empty string to start a conversation, then store the returned conversation_id for the next message from that same user.
Before this POST request, you can test the key with curl https://api.dify.ai/v1/info -H "Authorization: Bearer $DIFY_API_KEY".
curl example
curl -X POST 'https://api.dify.ai/v1/chat-messages' \
-H "Authorization: Bearer $DIFY_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"inputs": {},
"query": "Hello! What can you help me with?",
"response_mode": "blocking",
"conversation_id": "",
"user": "user-123"
}' Example response
{
"event": "message",
"message_id": "msg_456",
"conversation_id": "conv_789",
"answer": "Hello! What would you like to explore?",
"metadata": { "usage": { "prompt_tokens": 12, "completion_tokens": 10 } }
} Python example (using requests)
import os
import requests
API_KEY = os.environ["DIFY_API_KEY"]
BASE_URL = os.environ.get("DIFY_BASE_URL", "https://api.dify.ai/v1")
def chat(query, conversation_id="", user="user-123"):
response = requests.post(
f"{BASE_URL}/chat-messages",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"inputs": {},
"query": query,
"response_mode": "blocking",
"conversation_id": conversation_id,
"user": user,
},
timeout=(10, 120),
)
response.raise_for_status()
return response.json()
result = chat("What is Dify?")
print(result["answer"])
result2 = chat(
"Can you elaborate?",
conversation_id=result["conversation_id"],
)
print(result2["answer"]) user value when continuing a conversation. Dify scopes conversations, messages and uploaded files to that end-user value.
Streaming Responses (SSE)
With response_mode set to streaming, Dify returns Server-Sent Events. A chat stream can contain more than text tokens. Handle message, message_end, error and ping at minimum, and ignore unknown event types safely. Dify can report a stream error inside an HTTP 200 response, so inspect each event payload.
Streaming curl example
curl -X POST 'https://api.dify.ai/v1/chat-messages' \
-H "Authorization: Bearer $DIFY_API_KEY" \
-H 'Content-Type: application/json' \
--no-buffer \
-d '{
"inputs": {},
"query": "Write a short poem about AI.",
"response_mode": "streaming",
"conversation_id": "",
"user": "user-123"
}'
# Example message events; actual chunks and event types vary by app:
# data: {"event":"message","answer":"In"}
# data: {"event":"message_end"} Python streaming example
import json
import os
import requests
API_KEY = os.environ["DIFY_API_KEY"]
BASE_URL = os.environ.get("DIFY_BASE_URL", "https://api.dify.ai/v1")
def stream_chat(query, user="user-123"):
with requests.post(
f"{BASE_URL}/chat-messages",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"inputs": {},
"query": query,
"response_mode": "streaming",
"conversation_id": "",
"user": user,
},
stream=True,
timeout=(10, 300),
) as response:
response.raise_for_status()
for line in response.iter_lines(decode_unicode=True):
if not line or not line.startswith("data:"):
continue
event = json.loads(line[5:].lstrip())
event_type = event.get("event")
if event_type in {"message", "agent_message"}:
print(event.get("answer", ""), end="", flush=True)
elif event_type == "error":
raise RuntimeError(event.get("message", "Dify stream failed"))
elif event_type == "message_end":
print()
return
stream_chat("Explain quantum computing in simple terms.") Browser apps: use your own backend
Do not call Dify directly from browser JavaScript with an app API key. Send the user's request to your own authenticated backend. Your backend validates the user, adds the Dify key, calls the Service API, and returns only the response data the browser needs.
Browser -> your authenticated backend -> Dify Service API
Browser <- filtered response or SSE <- your backend Using the API with Self-Hosted Dify
A self-hosted Dify deployment uses its own Service API base URL, commonly your HTTPS domain followed by /v1. The same published app concepts apply, but do not assume that every Dify version and app type has an identical request or event shape. Check the API reference generated inside the deployed app and test GET /info before switching production traffic.
Dify Cloud
BASE_URL = "https://api.dify.ai/v1" Self-Hosted
BASE_URL = "https://your-server.com/v1" Self-hosting gives you control over the Dify infrastructure. It does not automatically keep every byte on that server. Requests can still reach external model providers, plugins, storage services and observability systems configured in the deployment. Review those data flows, retention settings and contracts separately. Budget for the VM, storage, backups, operations, model usage and any paid external services.
Best self-hosting options for API-heavy workloads
Affiliate disclosure: We may earn a commission if you buy through these provider links, at no additional cost to you. Prices and availability can change after publication.
Hetzner VPS (DIY)
Hetzner CX23 in Germany or Finland starts at 5.49 EUR per month excluding VAT and IPv4 for new orders since June 15, 2026. You operate Dify, TLS, updates, backups and recovery.
Get Hetzner →Elestio (Managed)
Elestio advertises managed Dify from 16 USD per month. The final estimate depends on cloud provider, region, resources and support level.
Get Elestio →Primary Sources
Use the API reference generated inside your published app for its exact routes and fields. These primary sources support the security, pricing and hosting details checked for this guide.
Frequently Asked Questions
How do I get a Dify API key?
Open the published app in Dify Studio, enter its API access area and create an app API key. Store it on your backend and send it as Authorization: Bearer YOUR_API_KEY. Use a stable user value for each end user.
Is the Dify API free to use?
The answer depends on the deployment and services you use. Dify Cloud plans include different message-credit allowances. A self-hosted deployment still has infrastructure, storage, backup, operations, model-provider and plugin costs. Check current Dify pricing and each configured provider before estimating total cost.
Can I stream Dify API responses?
Yes. Set response_mode to streaming to receive Server-Sent Events. Handle text, completion, error and keep-alive events according to the published app type. Current Agent apps support streaming only.
What programming languages work with the Dify API?
Any server-side language that can make HTTPS requests can call the Dify Service API. This guide uses curl and Python requests. You do not need an SDK, and you should not embed an app API key in browser or mobile client code.
Ready to Self-Host Dify?
Self-hosting can give you more control over deployment, upgrades and network boundaries, but it also makes you responsible for operations and recovery. Compare a self-managed VPS with a managed Dify service before choosing.