Streamlit has revolutionized the way we create data-driven web applications with Python. By integrating APIs into our Streamlit apps, we can take them to the next level, accessing real-time data and providing dynamic experiences for users.
In this guide, we'll explore how to integrate APIs with Streamlit applications, covering everything from basic requests to more advanced techniques.
Before we dive in, make sure you have Streamlit and the requests
library installed:
pip install streamlit requests
Let's start with a simple example using the Open Weather Map API. First, you'll need to sign up for a free API key at openweathermap.org.
Here's a basic Streamlit app that fetches weather data:
import streamlit as st import requests def get_weather(city): api_key = "YOUR_API_KEY" base_url = "http://api.openweathermap.org/data/2.5/weather" params = { "q": city, "appid": api_key, "units": "metric" } response = requests.get(base_url, params=params) return response.json() st.title("Weather Checker") city = st.text_input("Enter a city name:") if city: weather_data = get_weather(city) if weather_data["cod"] == 200: st.write(f"Temperature: {weather_data['main']['temp']}°C") st.write(f"Humidity: {weather_data['main']['humidity']}%") st.write(f"Description: {weather_data['weather'][0]['description']}") else: st.error("City not found. Please try again.")
This app allows users to enter a city name and displays the current weather information.
Many APIs require authentication. Let's look at an example using the GitHub API, which uses token-based authentication:
import streamlit as st import requests def get_github_repos(username, token): headers = {"Authorization": f"token {token}"} response = requests.get(f"https://api.github.com/users/{username}/repos", headers=headers) return response.json() st.title("GitHub Repository Viewer") username = st.text_input("Enter a GitHub username:") token = st.text_input("Enter your GitHub token:", type="password") if username and token: repos = get_github_repos(username, token) if isinstance(repos, list): for repo in repos: st.write(f"Repository: {repo['name']}") st.write(f"Description: {repo['description']}") st.write(f"Stars: {repo['stargazers_count']}") st.write("---") else: st.error("Unable to fetch repositories. Please check your credentials.")
This app securely handles the GitHub token and displays repository information for the given user.
APIs can power interactive components in your Streamlit app. Here's an example using the REST Countries API to create a dropdown of countries and display information about the selected country:
import streamlit as st import requests def get_countries(): response = requests.get("https://restcountries.com/v3.1/all") return response.json() def get_country_info(country_name): response = requests.get(f"https://restcountries.com/v3.1/name/{country_name}") return response.json()[0] st.title("Country Information Explorer") countries = get_countries() country_names = [country["name"]["common"] for country in countries] selected_country = st.selectbox("Select a country:", country_names) if selected_country: country_info = get_country_info(selected_country) st.write(f"Capital: {country_info['capital'][0]}") st.write(f"Population: {country_info['population']:,}") st.write(f"Area: {country_info['area']:,} km²") st.image(country_info['flags']['png'], width=200)
This app creates a dropdown menu of countries and displays information about the selected country, including its flag.
When working with APIs, it's crucial to handle rate limits and potential errors. Here's an example of how to implement error handling and respect rate limits:
import streamlit as st import requests import time def get_quote(api_key): url = "https://api.quotable.io/random" headers = {"Authorization": f"Bearer {api_key}"} try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes return response.json() except requests.exceptions.RequestException as e: st.error(f"An error occurred: {e}") return None st.title("Random Quote Generator") api_key = st.text_input("Enter your API key:", type="password") if st.button("Get Quote"): with st.spinner("Fetching quote..."): time.sleep(1) # Simulate respecting rate limits quote_data = get_quote(api_key) if quote_data: st.write(f"Quote: {quote_data['content']}") st.write(f"Author: {quote_data['author']}")
This example includes error handling and simulates respecting rate limits by adding a small delay between requests.
Integrating APIs with Streamlit applications opens up a world of possibilities for creating dynamic, data-driven web apps. By following these examples and best practices, you'll be well on your way to building powerful Streamlit applications that leverage the vast ecosystem of APIs available.
Remember to always read the documentation for the APIs you're using, handle errors gracefully, and respect rate limits to ensure your applications run smoothly and efficiently.
22/11/2024 | Python
14/11/2024 | Python
26/10/2024 | Python
05/10/2024 | Python
21/09/2024 | Python
05/11/2024 | Python
22/11/2024 | Python
25/09/2024 | Python
05/10/2024 | Python
06/10/2024 | Python
25/09/2024 | Python
17/11/2024 | Python