Health Universe
  • Core Concepts
    • Overview of Health Universe
    • How Health Universe Works
  • Building Apps in Health Universe
    • Getting started with Health Universe
      • Create a Health Universe Account
      • Create a Github Account
      • Link your Github Account to your Health Universe Account
    • Creating a Workspace
    • Developing your Health Universe App
      • Streamlit vs FastAPI
      • Working in Streamlit
        • Typical Project Setup
        • Your First Health Universe App
        • Streamlit Best Practices
      • Working in FastAPI
        • Typical Project Setup
        • Your First Health Universe App
        • Navigator FastAPI best practices
    • Deploying your app to Health Universe
      • Deploying to Health Universe
      • Secret Management
      • Connecting to an LLM
      • Connecting to an external data source
  • Testing your app
  • Re-deploying your app
  • Document your app
  • Deleting your App on Health Universe
  • Additional resources
    • Data Formats, Standards & Privacy
    • External Tools and Libraries
Powered by GitBook
On this page
  • Prerequisites
  • Step 1: Prepare Your Data
  • Step 2: Load the Data in Your App
  • Step 3: Create Endpoints for Filtering Data
  • Step 4: Add an Endpoint to Visualize the Data
  • Step 5: Run Your Healthcare App

Was this helpful?

  1. Building Apps in Health Universe
  2. Developing your Health Universe App
  3. Working in FastAPI

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 page

  • http://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.

PreviousTypical Project SetupNextNavigator FastAPI best practices

Last updated 24 days ago

Was this helpful?