> For the complete documentation index, see [llms.txt](https://docs.healthuniverse.com/overview/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.healthuniverse.com/overview/building-apps-in-health-universe/developing-your-health-universe-app/working-in-fastapi/your-first-health-universe-app.md).

# 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:

```python
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.

```python
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:

```python
@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:

```python
import plotly.express as px
```

Now, we’ll add a `/chart` endpoint that displays a bar chart showing the average blood pressure by age:

```python
@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:

```arduino
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.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.healthuniverse.com/overview/building-apps-in-health-universe/developing-your-health-universe-app/working-in-fastapi/your-first-health-universe-app.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
