Drop files here
or click to upload
import streamlit as st
import requests
import json
from streamlit.runtime.scriptrunner import get_script_run_ctx
# --- App Configuration ---
st.set_page_config(page_title="API Chatbot", layout="centered")
# --- API Details ---
# The endpoint URL and authorization token have been updated.
API_URL = "https://emea.snaplogic.com/api/1/rest/slsched/feed/ConnectFasterInc/snapLogic4snapLogic/Bootcamp_EMEA_August_2025/CRM_Retriever_Rajesh_Task"
AUTH_TOKEN = "1234"
# --- Helper Functions ---
def get_device_id():
ctx = get_script_run_ctx()
if ctx is not None:
return ctx.session_id
return "unknown_device"
def get_api_response(message):
headers = {
"Authorization": f"Bearer {AUTH_TOKEN}",
"Content-Type": "application/json",
}
# The payload has been updated to match the API's expected format: [{"Question": "..."}]
payload = json.dumps([
{"Question": message}
])
try:
response = requests.post(API_URL, headers=headers, data=payload)
response.raise_for_status() # Raises an HTTPError for bad responses (4xx or 5xx)
# The response parsing has been updated to match the API's format: [{"Response": "..."}]
api_response_data = response.json()
if api_response_data and isinstance(api_response_data, list) and len(api_response_data) > 0:
return api_response_data[0].get("Response", "Sorry, I couldn't get a response from the API.")
else:
return "Sorry, the API returned an unexpected response format."
except requests.exceptions.RequestException as e:
st.error(f"Error connecting to the API: {e}")
return "Sorry, I'm having trouble connecting right now. Please try again later."
# --- Streamlit UI ---
st.title("Streamlit API Chatbot")
st.markdown("Feel free to ask me anything!")
# Initialize chat history in session state if it doesn't exist
if "messages" not in st.session_state:
st.session_state.messages = []
# Display existing chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Handle user input
if prompt := st.chat_input("What is up?"):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Get and display the API's response
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
response = get_api_response(prompt)
st.markdown(response)
# Add the assistant's response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?