raomyousaf commited on
Commit
8167fe5
·
verified ·
1 Parent(s): 27828ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -49
app.py CHANGED
@@ -1,57 +1,54 @@
1
- import streamlit as st
2
  import requests
 
 
 
3
 
4
- # Function to fetch data from API
5
- def fetch_api_data(api_url, headers=None):
6
- try:
7
- # Bypass SSL verification for testing (set verify=False). Use with caution!
8
- response = requests.get(api_url, headers=headers, verify=False)
9
- if response.status_code == 200:
10
- return response.json()
11
- else:
12
- st.error(f"Failed to fetch data: {response.status_code} - {response.text}")
13
- return None
14
- except requests.exceptions.SSLError as ssl_error:
15
- st.error("SSL Error: Certificate verification failed.")
16
- st.error(str(ssl_error))
17
- return None
18
- except requests.exceptions.ConnectionError as conn_error:
19
- st.error("Connection Error: Unable to reach the server.")
20
- st.error(str(conn_error))
21
- return None
22
- except Exception as e:
23
- st.error(f"An unexpected error occurred: {str(e)}")
24
- return None
25
 
26
- # Streamlit app
27
- def main():
28
- st.title("API Data Viewer")
29
- st.markdown("""
30
- This app allows you to fetch and display data from an API.
31
- If the server uses an invalid SSL certificate, SSL verification can be bypassed for testing purposes.
32
- """)
33
 
34
- # Input API URL and optional API key
35
- api_url = st.text_input("Enter API URL", placeholder="https://api.example.com/data")
36
- api_key = st.text_input("Enter API Key (if required)", type="password", placeholder="Optional")
 
 
37
 
38
- # Fetch Data button
39
- if st.button("Fetch Data"):
40
- if api_url:
41
- # Set headers if API key is provided
42
- headers = {"Authorization": f"Bearer {api_key}"} if api_key else None
43
- data = fetch_api_data(api_url, headers)
44
-
45
- if data:
46
- st.success("Data fetched successfully!")
47
- st.json(data) # Display raw JSON data
48
 
49
- # Optionally show structured data in a table if the response is a list of objects
50
- if isinstance(data, list) and all(isinstance(item, dict) for item in data):
51
- st.write("Structured Data View:")
52
- st.dataframe(data)
53
- else:
54
- st.error("Please provide a valid API URL.")
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  if __name__ == "__main__":
57
- main()
 
 
 
 
 
 
1
  import requests
2
+ import sqlite3
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
 
6
+ # Fetch data from the non-SSL API (example API URL)
7
+ def fetch_data_from_api():
8
+ api_url = "http://example.com/api" # Replace with your actual non-SSL API URL
9
+ response = requests.get(api_url)
10
+ data = response.json() # Assumes the response is in JSON format
11
+ return data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # Store data in SQLite
14
+ def store_data_in_sqlite(data):
15
+ conn = sqlite3.connect('data.db')
16
+ cursor = conn.cursor()
 
 
 
17
 
18
+ # Create table if it does not exist
19
+ cursor.execute('''CREATE TABLE IF NOT EXISTS api_data (
20
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
21
+ name TEXT,
22
+ value INTEGER)''')
23
 
24
+ # Insert data into the database
25
+ for item in data:
26
+ cursor.execute("INSERT INTO api_data (name, value) VALUES (?, ?)", (item['name'], item['value']))
27
+
28
+ conn.commit()
29
+ conn.close()
 
 
 
 
30
 
31
+ # Function to retrieve data for the chart
32
+ def get_data_for_chart():
33
+ conn = sqlite3.connect('data.db')
34
+ df = pd.read_sql_query("SELECT name, value FROM api_data", conn)
35
+ conn.close()
36
+ return df
37
+
38
+ # Function to plot a chart
39
+ def plot_chart(df):
40
+ plt.figure(figsize=(8,6))
41
+ plt.bar(df['name'], df['value'])
42
+ plt.xlabel('Name')
43
+ plt.ylabel('Value')
44
+ plt.title('API Data Visualization')
45
+ plt.xticks(rotation=45)
46
+ plt.tight_layout()
47
+ plt.show()
48
 
49
  if __name__ == "__main__":
50
+ # Fetch, store data and visualize
51
+ data = fetch_data_from_api()
52
+ store_data_in_sqlite(data)
53
+ df = get_data_for_chart()
54
+ plot_chart(df)