Absolutely ✅ — here’s a full working FastAPI + Streamlit dashboard setup with a fallback method so your dashboard will always show data, even if the external API fails.


1️⃣ FastAPI (app.py) – Real-time + fallback

from fastapi import FastAPI
import requests

app = FastAPI()

@app.get("/bitcoin")
def get_bitcoin():
    """
    Fetch Bitcoin price from external API.
    If API fails (network issue, blocked, etc.), return fallback mock data.
    """
    try:
        # Primary API (CoinLore)
        r = requests.get("https://api.coinlore.net/api/ticker/?id=90", timeout=5)
        r.raise_for_status()
        data = r.json()
        return {"price": data[0]["price_usd"], "source": "CoinLore API"}
    except Exception:
        # Fallback mock data
        return {"price": 65000, "source": "mock fallback"}

Run FastAPI:

uvicorn app:app --reload --host 127.0.0.1 --port 8000

Check in browser:
http://127.0.0.1:8000/bitcoin


2️⃣ Streamlit Dashboard (dashboard.py) – Fetch + Display

import streamlit as st
import requests
import pandas as pd

st.title("Real-Time Data Dashboard")

# 1️⃣ Bitcoin Price
try:
    btc = requests.get("http://127.0.0.1:8000/bitcoin").json()
    st.subheader("Bitcoin Price")
    st.write(f"Price: ${btc['price']}  (Source: {btc['source']})")
except Exception as e:
    st.error(f"Could not fetch Bitcoin price: {e}")

# 2️⃣ Random Dog Image
try:
    dog = requests.get("https://dog.ceo/api/breeds/image/random").json()
    st.subheader("Random Dog")
    st.image(dog["message"], caption="Woof!", use_container_width=True)
except Exception as e:
    st.error(f"Could not fetch dog image: {e}")

# 3️⃣ COVID-19 Latest CSV Data
try:
    covid_url = "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/latest/owid-covid-latest.csv"
    df = pd.read_csv(covid_url)
    st.subheader("COVID-19 Latest Stats (Top 10 Rows)")
    st.dataframe(df.head(10))
    st.download_button("Download CSV", df.to_csv(index=False), "covid_data.csv")
except Exception as e:
    st.error(f"Could not fetch COVID data: {e}")

Run Streamlit:

streamlit run dashboard.py

Open in browser:
http://localhost:8501


✅ Notes:

  1. FastAPI runs on 127.0.0.1:8000. Keep this terminal open.
  2. Streamlit runs on localhost:8501. Keep in a separate terminal.
  3. Fallback mechanism:
    • If the CoinLore API fails, FastAPI returns a fixed mock price.
    • Streamlit will display it seamlessly.
  4. Other sources: Dog API and COVID CSV are public and should work without issues.

Pages: 1 2 3 4


Discover more from HintsToday

Subscribe to get the latest posts sent to your email.

Posted in

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading