Nawal20's picture
Rename app.py to app2.py
9ffe9ff verified
import streamlit as st
import requests
import json
# Digi-Key API and credentials
TOKEN_URL = "https://api.digikey.com/v1/oauth2/token"
API_URL = "https://api.digikey.com/products/v4/search/keyword"
CLIENT_ID = "K9d4a2AaGwQcoAvdNDZVYEOB3sqL4bMg" # Replace with your Digi-Key Client ID
CLIENT_SECRET = "NxzuxY67eJssGDkA" # Replace with your Digi-Key Client Secret
# Function to fetch access token
@st.cache_data(ttl=3500) # Cache the token for its lifespan (1 hour)
def fetch_access_token() -> str:
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
data = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"grant_type": "client_credentials",
}
response = requests.post(TOKEN_URL, headers=headers, data=data)
if response.status_code == 200:
token_data = response.json()
return token_data["access_token"]
else:
st.error(f"Failed to retrieve access token: {response.status_code} - {response.text}")
st.stop()
# Function to make API requests to Digi-Key
def search_digikey_components(keywords: str) -> dict:
access_token = fetch_access_token() # Get the token automatically
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
"X-DIGIKEY-Client-Id": CLIENT_ID,
}
payload = {
"Keywords": keywords,
"Limit": 10,
"Offset": 0,
"FilterOptionsRequest": {
"MarketPlaceFilter": "NoFilter",
},
"SortOptions": {
"Field": "None",
"SortOrder": "Ascending",
},
}
response = requests.post(API_URL, headers=headers, json=payload)
if response.status_code == 200:
return response.json()
else:
st.error(f"API request failed: {response.status_code} - {response.text}")
return {}
# Streamlit app interface
st.title("Digi-Key Circuit Component Advisor")
st.write(
"""
This app helps circuit designers search for electronic components using the Digi-Key API.
Enter the name of the component you are looking for to get detailed specifications and associated information.
"""
)
# Input for the user
keywords = st.text_input("Enter the name or keyword of the component:", "")
if keywords:
st.write(f"Searching for components matching: `{keywords}`...")
data = search_digikey_components(keywords)
if "Products" in data and data["Products"]:
st.header("Search Results")
for product in data["Products"]:
st.subheader(product["Description"]["ProductDescription"])
st.write(f"**Manufacturer**: {product['Manufacturer']['Name']}")
st.write(f"**Product Number**: {product['ManufacturerProductNumber']}")
st.write(f"**Unit Price**: ${product['UnitPrice']}")
st.write(f"[Datasheet]({product['DatasheetUrl']})")
st.write(f"[Product Link]({product['ProductUrl']})")
# Check if PhotoUrl exists and is not None
if product.get("PhotoUrl"):
st.image(product["PhotoUrl"], width=200)
else:
st.write("_Image not available_")
st.write("---")
else:
st.warning("No components found. Try using different keywords.")