Build and Deploy a Python Web App with Streamlit

Build an interactive Python web app with Streamlit, then deploy it free on Streamlit Community Cloud or on Railway in one click.

Streamlit turns a Python script into an interactive web app, with no HTML, CSS or JavaScript. You write ordinary Python, add widgets such as text inputs, dropdowns and buttons, and Streamlit reruns the script whenever someone changes one. It's a popular way for data scientists and developers to share dashboards, data explorers and AI demos.

To build and deploy a Streamlit app:

  1. Install Streamlit and write your app in a single Python file.
  2. Run it locally with streamlit run.
  3. Push it to GitHub with a requirements.txt.
  4. Deploy it on Streamlit Community Cloud for free, or on Railway in one click.

What is Streamlit?

Streamlit is an open-source Python library for building data apps. It works with the libraries data scientists already use, such as pandas, Matplotlib, Plotly and Altair, and has built-in charts, tables, maps and chat elements. Snowflake acquired Streamlit in March 2022. The library is still free and open source, and Snowflake also runs it as a managed service.

Streamlit home page
Source: Streamlit.io

Build a Stock Price App with Streamlit

Streamlit needs Python 3.11 or later. Install it along with yfinance, which reads Yahoo Finance data without an API key:

pip install streamlit==1.67.0 yfinance==1.8.0

The simplest Streamlit app is two lines. Save this as streamlit_app.py and run streamlit run streamlit_app.py:

import streamlit as st

st.write("Hello World!")

Streamlit opens the app in your browser at http://localhost:8501. Now replace the file with a small stock price app:

import streamlit as st
import yfinance as yf

st.title("Stock Price Explorer")

symbol = st.text_input("Ticker symbol", "AAPL").strip().upper()
period = st.selectbox("Period", ["1mo", "6mo", "1y", "5y"], index=1)

@st.cache_data(ttl=900)
def load_history(symbol, period):
    return yf.Ticker(symbol).history(period=period)

if symbol:
    try:
        data = load_history(symbol, period)
    except Exception as e:
        st.error(f"Couldn't fetch data: {e}")
        st.stop()

    if data.empty:
        st.error(f"No data found for {symbol}.")
    else:
        first, last = data["Close"].iloc[0], data["Close"].iloc[-1]
        st.metric(f"{symbol} close", f"{last:,.2f}", f"{(last - first) / first:+.2%}")
        st.line_chart(data["Close"])

Each time you change the ticker or the period, Streamlit reruns the script from top to bottom. @st.cache_data keeps each result for 15 minutes, so changing back and forth doesn't call Yahoo again. That matters because Yahoo rate-limits heavy use, especially from cloud servers.

Save your dependencies in a requirements.txt next to the app:

streamlit==1.67.0
yfinance==1.8.0

Then push both files to a GitHub repository.

Deploy on Streamlit Community Cloud

Streamlit Community Cloud is the quickest free way to share an app. It deploys straight from GitHub and redeploys whenever you push a change.

  1. Sign in to Community Cloud with GitHub and click Create app.
  2. Choose your repository, branch and streamlit_app.py as the main file. Under Advanced settings, you can pick the Python version and add secrets.
  3. Click Deploy. Your app gets a *.streamlit.app address.
Deploying a Streamlit app from a GitHub repository on Community Cloud
Deploy a Streamlit app from GitHub

An app's visibility follows its GitHub repository: a public repository gives you a public app, and a private repository gives you a private one. Community Cloud allows one private app at a time, which you can share by inviting people by email.

If your app needs an API key, don't put it in your code. Add it under Advanced settings > Secrets in TOML format, for example API_KEY = "your-key", and read it with st.secrets["API_KEY"]. To do the same locally, put the key in .streamlit/secrets.toml and add that file to .gitignore.

Deploy on Railway

Railway suits apps you'd rather not make public, or ones that need more resources or a database. My Stock Financial Analysis template deploys a fuller version of this app in one click: company details, price charts from 1 day to 5 years, earnings reactions and analyst metrics, with no API key needed.

Deploy on Railway

To deploy your own app instead, create a Railway project from your GitHub repository and set this as the start command:

streamlit run streamlit_app.py --server.port $PORT --server.address 0.0.0.0

Add any API keys as service variables and read them with os.environ. Then generate a public domain under the service's Networking settings. Railway's Free plan includes $1 of usage a month, which suits small apps that sleep when nobody is using them. New accounts also get a one-time $5 trial credit.

Streamlit Hosting Options Compared

Community Cloud is free and the easiest to set up, but you get one private app, and apps are meant for sharing rather than for production. Railway costs money once you go beyond the Free plan. In return, apps can be private without limits, and you can add a database or a custom domain. Snowflake also hosts Streamlit apps for teams that already keep their data there. You can also run a Streamlit app in a Google Colab notebook, which is handy for quick experiments.

More Streamlit Examples

Frequently Asked Questions

Is Streamlit free? Yes. The library is open source under the Apache 2.0 licence, and Streamlit Community Cloud hosts apps for free.

Can I make a Streamlit app private? On Community Cloud, yes: deploy from a private GitHub repository and invite viewers by email, with one private app at a time. For more, host the app yourself, for example on Railway, and add sign-in with st.login.

Why is my Streamlit app slow to load? Free hosting puts idle apps to sleep, so the first visit after a while has to wait for the app to start. Within the app, cache slow calls with @st.cache_data so they don't run again on every rerun.

Subscribe to alphasec

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe