Your First Health Universe App
With your development environment set up, it's time to create your first healthcare app using Health Universe and FastAPI. In this tutorial, we will guide you through building a simple healthcare data API that allows users to filter patient data and view visualizations through an interactive chart endpoint.
Prerequisites
First, make sure your development environment is ready. Install the necessary libraries:
pip install fastapi uvicorn python-multipart kaleido
Step 1: Prepare Your Data
For this tutorial, we'll use a sample dataset containing information about patients, such as age, gender, and health metrics. You can find a suitable dataset online or create a CSV file with the following columns: Patient_ID
, Age
, Gender
, Height
, Weight
, Blood_Pressure
, and Heart_Rate
.
Save the CSV file as patient_data.csv
in the data
directory of your project.
Step 2: Load the Data in Your App
To load the data in your app, we'll use the Pandas library. If you haven't installed Pandas, run the following command in your terminal:
pip install pandas
Next, open app.py
in your text editor or IDE and import the Pandas library by adding the following line at the beginning of the file:
import pandas as pd
Now, modify the app.py
file to load the patient data. This load the dataset when the app starts so it’s available to all endpoints.
from fastapi import FastAPI, Form
from typing import Annotated, Literal
from fastapi.responses import StreamingResponse
import pandas as pd
from io import BytesIO
import base64
import kaleido
app = FastAPI(
title="Healthcare Data API",
description=(
"A simple healthcare data API that allows users to filter patient data and view visualizations through an interactive chart endpoint."
),
version="1.0.0",
)
# Load the patient dataset on startup
df = pd.read_csv("data/patient_data.csv")
Save the app.py
file.
Step 3: Create Endpoints for Filtering Data
To allow users to filter the data based on age and gender, add your first endpoint: an API route that filters the data by age and gender:
@app.post("/filter-patients")
def filter_patients(
min_age: Annotated[int, Form()],
max_age: Annotated[int, Form()],
gender: Annotated[Literal["Male", "Female", "All"], Form()] = "All"
):
filtered = df[(df["Age"] >= min_age) & (df["Age"] <= max_age)]
if gender != "All":
filtered = filtered[filtered["Gender"] == gender]
return filtered.to_dict(orient="records")
This endpoint allows users to:
Set a minimum and maximum age
Choose to filter by gender (Male, Female, or All)
Step 4: Add an Endpoint to Visualize the Data
To visualize the filtered data, we'll create a bar chart showing the average blood pressure for each age group. First, install the Plotly library by running the following command in your terminal:
Next, import the Plotly library in app.py
by adding the following line at the beginning of the file:
import plotly.express as px
Now, we’ll add a /chart
endpoint that displays a bar chart showing the average blood pressure by age:
@app.post("/chart")
def blood_pressure_chart(
min_age: Annotated[int, Form()],
max_age: Annotated[int, Form()],
gender: Annotated[Literal["Male", "Female", "All"], Form()] = "All"
):
filtered = df[(df["Age"] >= min_age) & (df["Age"] <= max_age)]
if gender != "All":
filtered = filtered[filtered["Gender"] == gender]
if filtered.empty:
return {"error": "No data found for given filters."}
# Aggregate data by age
agg = filtered.groupby("Age")["Blood_Pressure"].mean().reset_index()
# Create a bar chart
fig = px.bar(
agg,
x="Age",
y="Blood_Pressure",
text="Blood_Pressure",
labels={"Blood_Pressure": "Average Blood Pressure"},
title="Average Blood Pressure by Age",
height=400
)
# Save chart to in-memory buffer
buffer = BytesIO()
fig.write_image(buffer, format="png")
buffer.seek(0)
return StreamingResponse(buffer, media_type="image/png")
This code calculates the average blood pressure for each age group and creates a bar chart using Plotly Express.
Save the app.py
file.
Step 5: Run Your Healthcare App
To run your healthcare data visualization app, open the terminal, navigate to your project directory, and run the following command:
uvicorn app:app --reload
Open your browser and visit:
http://127.0.0.1:8000
— Launch pagehttp://127.0.0.1:8000/docs
— Interactive Swagger UI
Congratulations! You have successfully created your first healthcare app using FastAPI that you can deploy to Health Universe and share with the world. You can now build on this foundation to create more advanced applications, incorporating machine learning models, additional visualizations, and user interactivity.
Last updated
Was this helpful?