Using the Kora API with Python
Each section starts with a question, followed by the Python code you need. The functions are independent: simply copy the ones you need, along with the initial configuration.
How do I configure API access?
The base URL and API key are read from environment variables (including from a .env). Each request sends the API key in the Authorization header as a Bearer token.
# .env
KORA_BASE_URL=https://...
KORA_API_KEY=la-tua-chiave
from typing import Dict, Any, Optional
import requests
import os
from dotenv import load_dotenv
load_dotenv()
KORA_BASE_URL: str = str(os.environ["KORA_BASE_URL"])
KORA_API_KEY: str = str(os.environ["KORA_API_KEY"])
# Authorization header used in all requests
HEADERS: Dict[str, str] = {"Authorization": f"Bearer {KORA_API_KEY}"}
The code uses verify=False, which disables TLS certificate verification. This is acceptable for testing but in production we recommend removing it and using a valid certificate.
How do I retrieve an organization's categories?
GET /Categories
The request returns all categories accessible with your API key. Each category includes an organizationGUID field, allowing you to group categories by organization. The category's guid is used to create a chat.
def get_categories() -> Dict[str, str]:
"""Retrieve all accessible categories."""
response = requests.get(
url=f"{KORA_BASE_URL}/Categories",
headers=HEADERS,
verify=False,
)
response.raise_for_status() # raise an exception for 4xx/5xx errors
return response.json()
# usage example
categories = get_categories()
for category in categories:
print(f"GUID: {category['guid']}, name: {category['name']}, ORG_GUID: {category['organizationGUID']}")
Response
[
{
"guid": "64sfg...",
"name": "test_category",
"organizationGUID": "6fgf..."
}
]
How do I create a new chat?
POST /Chat
Each chat belongs to a category. You need an organizationGUID and categoryGUID (both obtained from the previous request), and a title. The optional external_user parameter associates the chat with an external user.
def create_chat(organization_guid: str,
category_guid: str,
title: str,
external_user: Optional[Dict[str, str]] = None) -> Dict[Any, Any]:
"""Create a new chat for a category."""
payload: dict[str, Any] = {
"organizationGUID": organization_guid,
"categoryGUID": category_guid,
"title": title,
}
if external_user: # add the external user only if providede
payload["externalUser"] = external_user
response = requests.post(
url=f"{KORA_BASE_URL}/Chat",
headers=HEADERS,
json=payload,
verify=False,
)
response.raise_for_status()
return response.json()
# usage example: create a chat in the first category
category = categories[0]
chat = create_chat(
organization_guid=category["organizationGUID"],
category_guid=category["guid"],
title="Test API kora Python",
)
chat_guid = chat["chatGUID"] # save for subsequent API requests
Response
{
"chatGUID": "60f5ee65-e43a-4ab8-a83d-87436ab054b3",
"title": "Test API kora python",
"categoryGUID": "1de9c564-dbdb-4866-a68a-209bb427d1de",
"categoryName": "test",
"lastUpdate": "2026-10-12T15:24:48.6646769Z",
"externalUser": None
}
Example with an external user
chat = create_chat(
organization_guid=category["organizationGUID"],
category_guid=category["guid"],
title="Warranty question",
external_user={
"id": "u-4821",
"name": "Mario Rossi",
"email": "This email address is being protected from spambots. You need JavaScript enabled to view it. ",
},
)
How do I send a message in a chat?
POST /Chat/{chat_guid}/Messages → GET /Chat/{chat_guid}/Messages/{message_guid}/Stream
The process involves two steps. First, you send the question: the response contains a list of messages, with the last one having a PENDING status (response being generated). Then, you open the stream for that message and read the response chunks as they arrive.
The stream uses events that start with data: . A blank line marks the end of an event. The [DONE] value indicates successful completion, while [ERROR:...] indicates a problem.
def ask(chat_guid: str, question: str) -> None:
"""Send a question and print the response as it arrives."""
# 1) send the question
messages = requests.post(
f"{KORA_BASE_URL}/Chat/{chat_guid}/Messages",
json={"message": question},
headers=HEADERS,
verify=False,
)
messages.raise_for_status()
answer = messages.json()[-1] # the last message is the incoming response
if answer["status"] != "PENDING":
raise RuntimeError(f"Kora can't answer: {answer['status']}")
# 2) read the streamed response
url = f"{KORA_BASE_URL}/Chat/{chat_guid}/Messages/{answer['guid']}/Stream"
with requests.get(url, headers=HEADERS, stream=True, verify=False) as stream:
stream.raise_for_status()
lines = []
for line in stream.iter_lines(decode_unicode=True):
if str(line).startswith("data: "): # response chunk
lines.append(line[len("data: "):])
elif line == "" and lines: # a blank line marks the end of the event
piece, lines = "\n".join(lines), []
if piece == "[DONE]": # completed successfully
break
if piece.startswith("[ERROR:"):
raise RuntimeError(f"Kora can't answer: {piece}")
print(piece, end="", flush=True)
# usage example
ask(chat_guid=chat_guid, question="what can you do for me?")
The function prints the response but does not return it. If you need the complete response text, collect the piece values in a list instead of printing them, then return "".join(...) at the end.
How do I retrieve the message history of a chat?
GET /Chat/{chat_guid}/Messages
Returns the complete message history, ordered by messageIndex. The role field distinguishes user messages (user) from assistant responses (assistant).
def get_chat_messages(chat_guid: str):
"""Retrieve the message history of a chat."""
history = requests.get(
f"{KORA_BASE_URL}/Chat/{chat_guid}/Messages",
headers=HEADERS,
verify=False,
)
history.raise_for_status()
return history.json()
# usage example
for m in get_chat_messages(chat_guid=chat_guid):
print(f"[{m['role']}] {m['content']}")
Response
[
{
"guid": "aaff6450-dab4-4933-bcde-b5f0688725fb",
"messageIndex": 0,
"role": "user",
"content": "what can you do for me?",
"sentAt": "2026-10-14T07:58:57.168664Z",
"status": "COMPLETE",
"answerFound": True
},
{
"guid": "a1c44bf5-c47d-44f8-97b6-501ac71853cf",
"messageIndex": 1,
"role": "assistant",
"content": "I can help you manage and retrieve company information...",
"sentAt": "2026-10-14T07:58:57.168664Z",
"status": "COMPLETE",
"answerFound": False
}
]