# REST API Integration > Connect your QwryAI agents to any app or workflow with the QwryAI API > [!NOTE] > > **Paid plan required.** The QwryAI API works on the **Starter**, **Growth** and **Enterprise** plans. [View plans](/pricing) ## Overview The QwryAI API lets you put your agent's answers inside your own app, automate customer conversations and manage your workspace from code. The **Chat API** sends messages to an agent and streams its replies over Server-Sent Events, with structured error codes. The **Tools API** reads and changes the rest of your workspace, such as agents, conversations and sources, with the same API key. **Base URL:** ``` https://api.qwryai.com/api/v2 ``` > [card] Send Messages | /docs/api-reference/v2/streaming | Chat with your agents and stream their replies in real time. > [card] Manage AI Agents | /docs/api-reference/v2/agents | Read and update your agents and their settings with the Tools API. > [card] Access Data | /docs/api-reference/v2/conversation-search | Search conversations and read their messages. ## Quick Start **1. Get Your API Key** ![The API keys page under Workspace settings, with the Manage keys heading and the Create API key button.](annotated/01-api-keys.webp "Workspace settings › API keys") 1. Open your QwryAI dashboard. 2. Go to **Workspace settings** › **API keys**. 3. Select **Create API key**, keep **Chat with agents** switched on and select **Confirm**. Then open the new key's **⋯** menu and choose **Copy key**. ![The Create New API Key dialog with a switch for each permission the key can carry, starting with Chat with agents, and the Confirm button.](annotated/02-create-key.webp "Create New API Key: choose the key's permissions.") > [!WARNING] > > Keep your API key on your server and never put it in code that runs in the browser. **2. Get Your Agent ID** Call the `list_agents` tool with your key. Each agent in the response has an `id`; use it wherever this guide shows `YOUR_AGENT_ID`. ```bash curl -X POST 'https://api.qwryai.com/public/v1/tools/list_agents' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{}' ``` **3. Send Your First Message** Test your setup with a simple chat request: ```bash curl -X POST 'https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "message": "Hello! How can you help me?", "stream": false }' ``` **Expected Response:** ```json { "data": { "id": "5b0e7c1a-2f4d-4c55-9a51-6d8e3f2b9c10", "role": "assistant", "parts": [ { "type": "text", "text": "Hi! I can answer questions about our products, orders and shipping. What do you need?" } ], "metadata": { "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3", "userMessageId": "0c4f6a2e-8d13-4b7a-b0e9-1a2c3d4e5f60", "userId": null, "finishReason": "stop", "usage": { "credits": 1 } } } } ``` > [!NOTE] > > `stream` is `true` unless you set it. Send `"stream": false` to get the whole reply as one JSON response. **4. Continue the Conversation** QwryAI keeps the conversation history, so you don't resend earlier messages. Pass the `conversationId` from the last response to send a follow-up: ```bash curl -X POST 'https://api.qwryai.com/api/v2/agents/YOUR_AGENT_ID/chat' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -H 'Content-Type: application/json' \ -d '{ "message": "Tell me more about your pricing.", "conversationId": "fd5ae9e1-9b30-4503-b346-ccd4d7ef16a3", "stream": false }' ``` To link a new conversation to one of your users, pass a `userId` with the first message. See [User Conversations](/docs/api-reference/v2/user-conversations). ### Chat API Streaming The chat endpoint streams replies as Server-Sent Events. Each event is a `data:` line holding a JSON object with a `type`, and the stream ends with `data: [DONE]`. Join the `text-delta` events to build the reply, and read the `conversationId` from the `finish` event to continue the conversation. > [tab] Node.js > > ```javascript > // streamer.js (Node.js 18+) > > const apiKey = process.env.QWRYAI_API_KEY > const agentId = 'YOUR_AGENT_ID' > const apiUrl = `https://api.qwryai.com/api/v2/agents/${agentId}/chat` > > async function readAgentReply() { > const response = await fetch(apiUrl, { > method: 'POST', > headers: { > Authorization: `Bearer ${apiKey}`, > 'Content-Type': 'application/json', > }, > body: JSON.stringify({ > message: 'Do you ship to Canada?', > stream: true, > // conversationId: 'CONVERSATION_ID', // leave out to start a new conversation > }), > }) > > if (!response.ok) { > const { error } = await response.json() > throw new Error(`${error.code}: ${error.message}`) > } > > const reader = response.body.getReader() > const decoder = new TextDecoder() > let buffer = '' > let conversationId > > while (true) { > const { done, value } = await reader.read() > if (done) break > > buffer += decoder.decode(value, { stream: true }) > const lines = buffer.split('\n') > buffer = lines.pop() // keep a partial line for the next chunk > > for (const line of lines) { > if (!line.startsWith('data: ')) continue > const data = line.slice('data: '.length) > if (data === '[DONE]') continue > > const event = JSON.parse(data) > switch (event.type) { > case 'text-delta': > process.stdout.write(event.delta) > break > case 'finish': > conversationId = event.messageMetadata.conversationId > break > case 'error': > console.error('\nStream error:', event.errorText) > break > } > } > } > > console.log('\nConversation ID:', conversationId) > } > > readAgentReply().catch((error) => console.log('Error:', error.message)) > ``` > [tab] Python > > ```python > # streamer.py > > import json > import os > import requests > > api_key = os.environ['QWRYAI_API_KEY'] > agent_id = 'YOUR_AGENT_ID' > api_url = f'https://api.qwryai.com/api/v2/agents/{agent_id}/chat' > > def read_agent_reply(): > headers = { > 'Authorization': f'Bearer {api_key}', > 'Content-Type': 'application/json', > } > data = { > 'message': 'Do you ship to Canada?', > 'stream': True, > # 'conversationId': 'CONVERSATION_ID', # leave out to start a new conversation > } > > response = requests.post(api_url, json=data, headers=headers, stream=True) > if not response.ok: > error = response.json()['error'] > raise RuntimeError(f"{error['code']}: {error['message']}") > > conversation_id = None > for line in response.iter_lines(decode_unicode=True): > if not line or not line.startswith('data: '): > continue > payload = line[len('data: '):] > if payload == '[DONE]': > continue > > event = json.loads(payload) > if event['type'] == 'text-delta': > print(event['delta'], end='', flush=True) > elif event['type'] == 'finish': > conversation_id = event['messageMetadata']['conversationId'] > elif event['type'] == 'error': > print(f"\nStream error: {event['errorText']}") > > print(f'\nConversation ID: {conversation_id}') > > read_agent_reply() > ``` > [!TIP] > > For every stream event, including the events for client actions, see [Streaming](/docs/api-reference/v2/streaming). ## Error Handling Errors come back with a machine-readable `code`: ```json { "error": { "code": "RATE_LIMIT_TOO_MANY_REQUESTS", "message": "Too many requests, please try again later" } } ``` Every Chat API response has an `x-request-id` header; include it when you contact support. See [Error Handling](/docs/api-reference/v2/error-handling) for every code and [Rate limiting](/docs/api-reference/v2/authentication#rate-limiting) for limits and retries. ## Performance Best Practices > [!TIP] > > **Ways to speed things up:** > > * Stream chat replies so your users see the answer while it's written. > * Reuse the `conversationId` for follow-ups instead of starting new conversations. > * Cache answers where it makes sense. > * After a `429` response, wait for the seconds in the `Retry-After` header before you try again. > * Use the `cursor` to [page through](/docs/api-reference/v2/pagination) long lists of conversations and sources. ### Key API Endpoints > [card] Chat API | /docs/api-reference/v2/streaming | Send messages and stream your agent's replies. > [card] AI Agent Management | /docs/api-reference/v2/agents | Read and configure your agents with the Tools API. > [card] Conversations | /docs/api-reference/v2/conversation-search | Search chat history and read conversation messages. > [card] Sources | /docs/api-reference/v2/sources | Add and manage the sources your agents learn from. > [card] API Overview | /docs/api-reference/v2/overview | The full reference: authentication, streaming, client actions and pagination.