Skip to content

Instantly share code, notes, and snippets.

@sefgit
Forked from raphaeljolivet/api.py
Created May 2, 2025 01:14
Show Gist options
  • Save sefgit/7405b05f2d59aa03e74e706a50cfb6a3 to your computer and use it in GitHub Desktop.
Save sefgit/7405b05f2d59aa03e74e706a50cfb6a3 to your computer and use it in GitHub Desktop.
Add custom rest API to streamlit app
# This code adds custom REST api handler at runtime to a running Streamlit app
#
from tornado.web import Application, RequestHandler
from tornado.routing import Rule, PathMatches
import gc
import streamlit as st
@st.cache_resource()
def setup_api_handler(uri, handler):
print("Setup Tornado. Should be called only once")
# Get instance of Tornado
tornado_app = next(o for o in gc.get_referrers(Application) if o.__class__ is Application)
# Setup custom handler
tornado_app.wildcard_router.rules.insert(0, Rule(PathMatches(uri), handler))
# Usage
class HelloHandler(RequestHandler):
def get(self):
self.write({'message': 'hello world'})
# This setup will be run only once
setup_api_handler('/api/hello', HelloHandler)
@sefgit
Copy link
Author

sefgit commented May 2, 2025

http://smthng/api/hello?my_arg=hi
self.get_argument("my_arg", "default value")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment