2

Dear Community Members,

I am new to FastAPI and I am trying to display the pandas dataframe as FastAPI output but I am not able to get the desired result. Here is something I am have done:

from fastapi import FastAPI, Body, Request, Form
from pydantic import BaseModel
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import pandas as pd

app = FastAPI()
templates = Jinja2Templates(directory="htmlDirectory")

class NameValues(BaseModel):
    Check : str = None

@app.get("/home", response_class = HTMLResponse)
def home(request:Request):
    return templates.TemplateResponse("introduction.html", {"request": request})

@app.post("/displayDF")
async def handle_df(Check: str = Form(...)):
    print("User input : ", Check)

    test_list = [["Joe", 34, "Accounts", 10000], ["Jack", 34, "Chemistry", 20000]]
    data = pd.DataFrame(data=test_list, columns=["Name", "Age", "Dept.", "Salary"])

    return data.to_html()

The output displays like below screenshot:

enter image description here

Is there a way to actually get the output in pandas dataframe format? Something like below :

enter image description here

Also, below is the "htmlDirectory" code, if some changes has to be done here.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
<h2>Please enter a string in the space provided</h2>

<form action="/displayDF" method="post">
    <input type="text" name="Check">
    <input type="submit">
</form>

</body>
</html>

1 Answer 1

5

One way to display your DataFrame is to generate a new HTML page using Jinja which will use your DataFrame HTML representation (thanks to df.to_html() method).

You can update your function like this example:

@app.post("/displayDF")
async def handle_df(request: Request, Check: str = Form(...)):
    print("User input : ", Check)
    test_list = [
        ["Joe", 34, "Accounts", 10000], ["Jack", 34, "Chemistry", 20000]
    ]
    data = pd.DataFrame(
        data=test_list,
        columns=["Name", "Age", "Dept.", "Salary"]
    )
    return templates.TemplateResponse(
        'df_representation.html',
        {'request': request, 'data': data.to_html()}
    )

df_representation.html (you've to create this new file under htmlDirectory folder):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>displayDF</title>
</head>
<body>
<h2>DataFrame representation:</h2>
<!-- You've to mark your data as safe,
    otherwise it'll be rendered as a string -->
    {{ data|safe }}
</body>
</html>

Result:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>displayDF</title>
</head>
<body>
<h2>DataFrame representation:</h2>
    <table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Name</th>
      <th>Age</th>
      <th>Dept.</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Joe</td>
      <td>34</td>
      <td>Accounts</td>
      <td>10000</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Jack</td>
      <td>34</td>
      <td>Chemistry</td>
      <td>20000</td>
    </tr>
  </tbody>
</table>
</body>
</html>

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to download this output dataframe as excel, just like how we do "data.to_excel" in pandas? I can add a download button to the browser but little confused as how to download the dataframe as excel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.