ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • AI Coaching
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

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

  • PyTorch Mastery: From Basics to Advanced

    14/11/2024 · Python

  • TensorFlow Mastery: From Foundations to Frontiers

    06/10/2024 · Python

  • Mastering NLP with spaCy

    22/11/2024 · Python

  • Python Basics: Comprehensive Guide

    21/09/2024 · Python

  • Django Mastery: From Basics to Advanced

    26/10/2024 · Python

Related articles

  • Deploying Streamlit Apps on the Web

    15/11/2024 · Python

  • Mastering Python Packaging and Distribution with Poetry

    15/01/2025 · Python

  • Unveiling Response Synthesis Modes in LlamaIndex

    05/11/2024 · Python

  • Building Microservices Architecture with FastAPI

    15/10/2024 · Python

  • Understanding Data Types in LangGraph

    17/11/2024 · Python

  • Mastering NumPy Linear Algebra

    25/09/2024 · Python

  • Mastering Error Handling in LangGraph

    17/11/2024 · Python

Popular category

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