1. Introduction to Streamlit
Streamlit is an open-source Python library that allows you to build interactive web applications for data science and machine learning projects—without needing any web development experience. It transforms Python scripts into beautiful, shareable web apps in just a few lines of code.
Key features of Streamlit:
- Designed for data scientists and developers who work mainly in Python.
- Requires no HTML, CSS, or JavaScript knowledge.
- Supports integration with popular libraries like Pandas, NumPy, Matplotlib, Plotly, and scikit-learn.
- Automatically updates the app when the underlying code changes.
- Can be deployed easily on platforms like Streamlit Community Cloud, Google Cloud Run, Heroku, or AWS.
2. Why Use Streamlit?
Streamlit stands out among other frameworks because it focuses on simplicity and speed. Here’s why many developers prefer it:
- Minimal Code, Maximum Output
You can create a fully functional data app with just a few lines of Python. For example:import streamlit as st st.write("Hello, Streamlit!")Running this file instantly displays a live web app. - Instant Feedback Loop
Streamlit runs in an interactive mode. When you edit the Python file, the app updates automatically. - Great for Data Visualization
It can render charts, tables, and plots from libraries like:- Matplotlib
- Plotly
- Seaborn
- Altair
- Bokeh
- PyDeck (for 3D map visualizations)
- Widgets for Interactivity
Streamlit provides a rich set of widgets—like sliders, buttons, checkboxes, and select boxes—that allow users to interact with your data. - Easy Deployment
You can deploy your app publicly using Streamlit Community Cloud or deploy privately on your own infrastructure.
3. Streamlit Installation and Setup
Before running Streamlit, ensure you have Python 3.8 or above installed on your system.
Step 1: Create a Virtual Environment (Recommended)
Creating a virtual environment helps isolate your dependencies.
On Windows:
python -m venv streamlit_env streamlit_env\Scripts\activate
On macOS/Linux:
python3 -m venv streamlit_env source streamlit_env/bin/activate
Step 2: Install Streamlit
Once your virtual environment is active, install Streamlit using pip:
pip install streamlit
To verify the installation:
streamlit --version
You should see an output like:
Streamlit, version 1.38.0
4. Creating Your First Streamlit Application
Let’s create a simple “Hello Streamlit” app to understand the basics.
Step 1: Create a Python File
Create a file named app.py in your working directory.
Step 2: Add the Following Code
import streamlit as st
# Title of the app
st.title("Welcome to Streamlit!")
# Add a simple text message
st.write("Hello, Streamlit! This is your first web app.")
# Display a number input and show its square
number = st.number_input("Enter a number", min_value=0)
st.write("Square of the number is:", number ** 2)
Step 3: Run the App
In your terminal, run:
streamlit run app.py
Step 4: Open the Browser
Once you run the command, Streamlit automatically starts a local server and opens your default browser at:
http://localhost:8501
You will see your web app live and interactive!
5. Understanding Streamlit’s Core Concepts
a. Writing Text
Streamlit provides multiple functions for text:
st.title("Main Title")
st.header("Section Header")
st.subheader("Subsection")
st.text("Plain text")
st.markdown("**Bold text using Markdown**")
b. Displaying Data
You can easily display Pandas DataFrames or charts:
import pandas as pd
import numpy as np
data = pd.DataFrame({
'x': np.arange(10),
'y': np.random.randn(10)
})
st.write("Data Table:", data)
st.line_chart(data)
c. Adding Widgets
Widgets make the app interactive:
name = st.text_input("Enter your name:")
age = st.slider("Select your age:", 1, 100, 25)
agree = st.checkbox("I agree to the terms")
if agree:
st.write(f"Hello {name}, you are {age} years old!")
d. Displaying Images and Media
Streamlit can show images, videos, and audio directly.
from PIL import Image
image = Image.open("example.png")
st.image(image, caption="Example Image", use_column_width=True)
st.video("example.mp4")
st.audio("example.mp3")
6. Running and Managing Streamlit Applications
Step 1: Running the App
As mentioned earlier, use:
streamlit run app.py
This starts a local development server.
Step 2: Stop the Server
To stop the app, press CTRL + C in your terminal.
Step 3: Run on a Specific Port
If port 8501 is busy, specify another port:
streamlit run app.py --server.port 8502
Step 4: View Logs
Use the --logger.level argument to see debug information:
streamlit run app.py --logger.level=debug
Step 5: Automatically Reload the App
Streamlit automatically reloads when you save changes to your script, so you can see updates in real time.
7. Advanced Features
a. Session State (Maintaining User Data)
Streamlit provides st.session_state to persist data between reruns.
if 'count' not in st.session_state:
st.session_state.count = 0
if st.button("Increment"):
st.session_state.count += 1
st.write("Counter:", st.session_state.count)
b. Layout Management
Use columns and containers to structure your UI.
col1, col2 = st.columns(2)
col1.write("This is column 1")
col2.write("This is column 2")
with st.container():
st.write("This is inside a container.")
c. Caching and Performance Optimization
To cache results of expensive computations:
@st.cache_data
def load_data():
import time
time.sleep(2)
return {"data": [1, 2, 3]}
st.write(load_data())
Caching improves performance by storing function results and reusing them instead of re-running every time.
8. Deployment of Streamlit Apps
Once your app is ready, you can deploy it.
Option 1: Streamlit Community Cloud
- Push your code to GitHub.
- Visit https://streamlit.io/cloud.
- Connect your GitHub account.
- Choose your repository and click “Deploy.”
Option 2: Using Docker
You can containerize your Streamlit app:
FROM python:3.10 WORKDIR /app COPY . /app RUN pip install streamlit pandas numpy EXPOSE 8501 CMD ["streamlit", "run", "app.py", "--server.port=8501", "--server.address=0.0.0.0"]
Then build and run:
docker build -t streamlit-app . docker run -p 8501:8501 streamlit-app
Option 3: Deploy on Cloud Platforms
You can also deploy on:
- Google Cloud Run
- AWS Elastic Beanstalk
- Azure App Service
- Heroku (free tier limited)
9. Common Errors and Troubleshooting
| Problem | Cause | Solution |
|---|---|---|
| App not launching | Port already in use | Run on another port using --server.port |
| Image/Media not loading | Wrong file path | Use absolute path or os.path.join |
| Slow performance | Large dataset or computation | Use @st.cache_data to cache |
| Widgets not updating | Code reruns incorrectly | Use st.session_state for managing widget state |
10. Example: A Simple Data Dashboard
Here’s a small example combining all concepts:
import streamlit as st
import pandas as pd
import numpy as np
st.title("Sales Dashboard")
# Generate sample data
data = pd.DataFrame({
"Month": pd.date_range("2025-01-01", periods=12, freq="M"),
"Sales": np.random.randint(2000, 5000, 12)
})
# Filter by threshold
threshold = st.slider("Minimum Sales:", 2000, 5000, 3000)
filtered_data = data[data["Sales"] >= threshold]
# Display
st.write("Filtered Data", filtered_data)
st.line_chart(filtered_data.set_index("Month"))
When you run this script, you’ll see an interactive sales dashboard that lets you filter data using a slider.
11. Conclusion
Streamlit is a powerful yet simple framework for transforming Python scripts into interactive web apps. It eliminates the complexity of frontend development and focuses purely on data and interactivity.
By mastering Streamlit, you can:
- Build custom dashboards for data analysis.
- Create ML model demos.
- Build prototypes for user feedback.
- Deploy production-ready data apps.
With just a few lines of Python, Streamlit empowers you to bring your ideas to life instantly.
