logologo
  • AI Interviewer
  • XpertoAI
  • MVP Ready
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Integrating APIs with Streamlit Applications

author
Generated by
ProCodebase AI

15/11/2024

python

Sign in to read full article

Introduction to API Integration in Streamlit

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.

Setting Up Your Environment

Before we dive in, make sure you have Streamlit and the requests library installed:

pip install streamlit requests

Making Basic API 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.

Handling API Authentication

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.

Creating Interactive Components with API Data

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.

Handling API Rate Limits and Errors

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.

Conclusion

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.

Popular Tags

pythonstreamlitapi integration

Share now!

Like & Bookmark!

Related Collections

  • Django Mastery: From Basics to Advanced

    26/10/2024 | Python

  • FastAPI Mastery: From Zero to Hero

    15/10/2024 | Python

  • LangChain Mastery: From Basics to Advanced

    26/10/2024 | Python

  • Mastering NLP with spaCy

    22/11/2024 | Python

  • Mastering Scikit-learn from Basics to Advanced

    15/11/2024 | Python

Related Articles

  • Mastering Regression Models in Scikit-learn

    15/11/2024 | Python

  • Debugging and Visualizing PyTorch Models

    14/11/2024 | Python

  • Unlocking Multilingual Power

    14/11/2024 | Python

  • Setting Up Your Python Development Environment for Streamlit Mastery

    15/11/2024 | Python

  • Mastering Unit Testing and Test Automation in Python

    15/01/2025 | Python

  • Mastering Pandas String Operations

    25/09/2024 | Python

  • Leveraging LangChain for Enterprise-Level Python Applications

    26/10/2024 | Python

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design