I'm experimenting with a FastAPI app GraphQL and some made up fake data for learning purposes:
import strawberry
from fastapi import FastAPI
from strawberry.asgi import GraphQL
import pandas as pd
# Sample DataFrame with temperature readings for three zones
data = {'Zone1_Temp': [20, 21, 19], 'Zone2_Temp': [22, 23, 21], 'Zone3_Temp': [24, 25, 23]}
df = pd.DataFrame(data)
@strawberry.type
class Query:
@strawberry.field
def average_zone_temp(self) -> float:
return df.mean().mean()
@strawberry.field
def coldest_zone_temp(self) -> str:
coldest_temp = df.min().min()
coldest_zone = df.idxmin()[df.min() == coldest_temp].index[0]
return f"{coldest_zone} with {coldest_temp} degrees C"
@strawberry.field
def warmest_zone_temp(self) -> str:
warmest_temp = df.max().max()
warmest_zone = df.idxmax()[df.max() == warmest_temp].index[0]
return f"{warmest_zone} with {warmest_temp} degrees C"
schema = strawberry.Schema(query=Query)
graphql_app = GraphQL(schema)
app = FastAPI()
app.add_route("/graphql", graphql_app)
which appears to work fine when using a Python script to retrieve that query of made up data:
import requests
import json
# Endpoint URL
url = 'http://192.168.0.102:8000/graphql'
def make_graphql_query(query: str):
# Headers
headers = {
'Content-Type': 'application/json'
}
# Make the POST request
response = requests.post(url, headers=headers, json={'query': query})
# Parse and return the response
if response.status_code == 200:
return json.dumps(response.json(), indent=4)
else:
return f"Query failed with status code {response.status_code}. Query: {query}"
# Separate queries for average, coldest, and warmest temperatures
query_avg = '{ averageZoneTemp }'
query_coldest = '{ coldestZoneTemp }'
query_warmest = '{ warmestZoneTemp }'
print("Average Temperature:")
print(make_graphql_query(query_avg))
print("\nColdest Temperature:")
print(make_graphql_query(query_coldest))
print("\nWarmest Temperature:")
print(make_graphql_query(query_warmest))
This will print back:
Average Temperature:
{
"data": {
"averageZoneTemp": 22.0
}
}
Coldest Temperature:
{
"data": {
"coldestZoneTemp": "Zone1_Temp with 19 degrees C"
}
}
Warmest Temperature:
{
"data": {
"warmestZoneTemp": "Zone3_Temp with 25 degrees C"
}
}
BUT this FastAPI app also appears to have a browser tool which I am having issues with:
It seems like no matter what I try in this Variable
and Header
section I either get an invalid JSON Error message or even this when I run it with nothing:
{
"data": null,
"errors": [
{
"message": "Syntax Error: Unexpected <EOF>.",
"locations": [
{
"line": 31,
"column": 1
}
]
}
]
}
Not a lot of wisdom here at all so any tips appreciated... Am stumped why the python script works but the Graphi
tool does not.