Build a GUI for Any API easily in Python Using Streamlit
Quickly implement a user interface for any API!
Hello World!

Today we are going to take another look at the awesome Python package named “Streamlit”. Streamlit is an awesome tool to build and share data applications for those who have never heard of this Python package.
If you want to have a look at what it can do, be sure to check out its website:
In today’s example, we are going to take 2 web APIs (agify and genderize) and implement both inside a single Streamlit dashboard. The final result is going to be similar to this one:


0. Requirements and Target
For this tutorial you’ll need:
- Python 3.x
- The following packages: Streamlit, requests_html, matplotlib, and pandas
- Basic knowledge of Python
We are going to install the requirements (except for Python) in the next step.
The tutorial is targeted at:
- Python intermediate programmers
- People who need a fast method to create a GUI for an API
1. Installing the requirements
The first thing we need to do is to install all the requirements:
pip install streamlit pip install requests-html pip install pandas pip install matplotlib
Here’s a brief description of these packages:
- streamlit: This is the package we are going to use to manage our GUI
- requests-HTML: This is an awesome package to scrape the web. I’ve written a few tutorials about it, so check them out if you’re interested.
- pandas: This is the go-to package for data frames in Python. If you are interested in becoming a Data Scientist, you’ll need to know this package.
- matplotlib: This is the basic Python visualization module, maybe not the best looking but one of the most complete
2. The APIs
For today’s tutorial we are going to use the following APIs:
- Agify: Agify.io predicts the age of a person given their name.
- Genderize: A simple API to predict the gender of a person given their name
I’ve found these two from the incredibly useful list of APIs on this Github repo:
For these two you won’t need an API key (for up to 1000/names a day), so they are pretty handy for examples like this.
So how do these APIs work? The first thing we need to do is build the URL for the HTTP Get request:
https://api.agify.io?name=michael&country_id=US
There are two parameters in this request:
- Name: This is required and it’s the name to predict the age for
- Country_id: this is optional and it narrows the results to a specific country
If you copy that URL and you paste it into your browser you should see something similar to this:
{"age":54,"count":108496,"country_id":"US","name":"michael"}This is a JSON containing the response to our request. In our Python code, we are going to parse this object to extract the information we need in our GUI.
The other API (genderize) works in the same way.
3. The Code
We can now start working on the code. Let’s start by importing all the requested packages and defining the HTTP session object:
import streamlit as st
from requests_html import HTMLSession
import matplotlib.pyplot as plt
import pandas as pd
sess = HTMLSession()There is not much to say about this part of the code. If you have any problem importing the packages, go back to chapter 1 and check if you’ve installed all the requirements correctly.
We can now define the main function that will retrieve the data from the APIs:
def get_data(in_name, in_country = None):
if in_country and in_country != '':
gender_url = f"https://api.genderize.io?name={in_name}&country_id={in_country}"
age_url = f"https://api.agify.io?name={in_name}&country_id={in_country}"
else:
gender_url = f"https://api.genderize.io?name={in_name}"
age_url = f"https://api.agify.io?name={in_name}"
gender_json = sess.get(gender_url).json()
age_json = sess.get(age_url).json()
return gender_json, age_jsonLet’s have a quick look at the code above:
- The first part of the code checks if the parameter “in_country” has been passed to the function. If there is none or it’s empty then only the “name” parametwill to be sent to the API, otherwise both are sent.
- Once we’ve built the URLs we can now trigger the requests and then convert them from JSON to a Python dictionary by using the “JSON” method of the request.
- Finally, we return both the results from the two APIs
If you run this function you should now be able to call the APIs and get a response from them.
Now that we’ve built our core function we can start defining the Streamlit interface:
def return_pie_values(in_gender_data):
if in_gender_data['gender'] == 'male':
return [in_gender_data['probability'], 1 - in_gender_data['probability']]
else:
return [1 - in_gender_data['probability'], in_gender_data['probability']]
st.title('Name Analyzer')
st.markdown("## Search")
# We define the inputs
name = st.text_input("Name", "Andrea")
country = st.text_input("Country")
# Here we create a button named run that only runs the code if pressed
if st.button("Run"):
### We retrieve the data ------------------
gender, age = get_data(name, country)
### We show the results for the Age API ---
st.markdown("## Results Age")
st.metric("Predicted Age", value = age['age'])
st.metric("Count", value = age['count'])
st.markdown("---")
### We show the results for the Gender API ---
st.markdown("## Results Gender")
# We define a Dataframe and a plot
df = pd.DataFrame({"category":["M","F"], "value":return_pie_values(gender)})
fig, ax = plt.subplots()
# Change background color to transparent
fig.patch.set_facecolor('none')
ax.pie(df['value'], labels = df['category'], autopct='%1.1f%%', colors = ['blue', 'fuchsia'], textprops={'color':"w"})
st.pyplot(fig)
st.metric("Count", gender['count'])
st.markdown("---")Let’s have a look at the code:
- The function in the code above is used to convert our “genderize” JSON into a list containing the probability percentages for male and female
- Below the function, we define the objects contained inside the page. We have markdown, text inputs, metrics, and pyplot objects. You can learn more about them by going to the official Streamlit docs.
- After we’ve defined the inputs we then create a button to press to run our “get_data” function.
- With the data parsed from the API, we build the visualizations by using metrics (for the numbers) and a pie chart made in matplotlib (for the gender probabilities).
4. Running the app
Now that we’ve completed our code, we need to run the application. To do this you need to open the folder in which you’ve written the code and open a terminal (a quick way to do that on Windows is to shift-right-click on the blank space of a folder and choose: “Open in terminal”)

Once you’ve opened the terminal you just need to write the following command (you’ll probably need to change the last part to your Python file name):
streamlit run .\streamlit_api.pyYou should now see an output similar to this:

If the browser does not open automatically on that URL, you can just copy and paste it into any browser. Once the page has loaded you should see the elements we’ve just written in our code:

Check out my GitHub for the complete code of this project.
Donations and stuff
If you’d like to support me consider subscribing to Medium using my referral:
If you don’t want to activate a subscription plan, but you’d still like to support me consider buying my music from Bandcamp:
Other URLs:
Personal Website: https://inzaniak.github.io Social Links: https://inzaniak.github.io/links.html Linkedin: https://www.linkedin.com/in/umberto-grando-a8527b150/

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord. Interested in Growth Hacking? Check out Circuit.



