Member-only story
How To Make HTTP Requests in Streamlit App
Utilizing requests or aiohttp packages
Since its inception, Streamlit has been gaining immense popularity among developers for building data applications in Python. It released its official 1.0 version on Oct 5, 2021. For your information, Streamlit is —
“… an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science.”
— Streamlit Docs
By utilizing Streamlit, you can easily build a simple frontend interface to demonstrate the functionality of your project. This is extremely helpful as you don’t need to deal with HTML, CSS, and JavaScript on your own. The web interface is coded directly in Python, making it easier to integrate with any ML and AI models.
Having said that, there may arise a situation where your application has to make external HTTP requests to other endpoints. This includes getting data from a remote server, processing the content via an intermediate endpoint, etc.
By reading this article, you will learn to make HTTP requests in the Streamlit application via the following Python packages depending on your use cases:
requests
— for normal applicationsaiohttp
— for applications that need to be executed asynchronously
To keep it simple and short, the functionality of the application is as follows:
- a number input widget that represents the ID of an image
- a submit button widget to call an external image API and parse the output as JSON
- an image widget to display the returned image URL and author name
The external image API is provided by Picsum, which is The Lorem Ipsum for photos:
https://picsum.photos/id/{id}/info
id represents the unique identifier and we will limit the value to be between 0 and 100. The API output is as follows:
{
"id": "0",
"author": "Alejandro Escamilla",
"width": 5616,
"height": 3744,
"url": "https://unsplash.com/...",
"download_url": "https://picsum.photos/..."
}