2

I have develope an API via FastAPI.

This API will do:

  1. POST with user_ip in client.py
  2. Use BigQuery API Client to query from data table in v1_router.py
  3. If user_ip exist in data table, return his group

The response time will cost 5 sec in my computer.

I have try to use time function to analyze:

3 sec : instance bigquery.Client in v1_router.py

2 sec : do client.query and res.to_dataframe().to_dict(orient='records')

Can Someone suggest me how to improve the response time ?

Thanks!

Project Folder Structure

│  client.py
│  main.py
│
├─routers
│  │  v1_router.py
│  │  __init__.py

Data Table

user_ip group
a12345  1, 2
b12345  1, 3
c12345  3
d12345  2
e12345  3, 1, 2
f12345  1
g12345  3
h12345  1
i12345  1
j12345  2
k12345  3

FastAPI

main.py

from fastapi import FastAPI
import uvicorn
from routers import v1_router

app = FastAPI()

app.include_router(v1_router)

if __name__ == "__main__":
    uvicorn.run(app="main:app", host="0.0.0.0", port=8000, reload=True)

/routers/v1_router.py

from fastapi import APIRouter
from google.cloud import bigquery
from pydantic import BaseModel

v1_router = APIRouter(
    prefix="/v1",
    )

client = bigquery.Client()

class User(BaseModel):
    ip: str

@v1_router.post("")
async def get_recommend(user: User):
    user_ip = user.ip

    QUERY = (f"""
        SELECT group
        FROM dataset.datatable
        WHERE user_ip = '{user_ip}'
    """)
    query_job = client.query(QUERY)

    res = query_job.result()

    res = res.to_dataframe().to_dict(orient='records')

    return res

client.py

import requests

host = "http://localhost:8000/"
url = f"{host}v1/"

user = {"ip": "f12345"}

res = requests.post(url, json=user)

if res.status_code == 200:
    print(res.json())
else:
    print("Error: ", res.text)

Xiang
  • 230
  • 2
  • 10
  • Please have a look at [this answer](https://stackoverflow.com/a/71205127/17865804), as well as [this answer](https://stackoverflow.com/a/73580096/17865804) and [this answer](https://stackoverflow.com/a/73694164/17865804) regarding the dataframe part and returning the results. – Chris Mar 25 '23 at 08:31

0 Answers0