An HTTP API for sensor data · Learning
English translation
Execution conditions
Requires fastapi and httpx. Use uvicorn additionally only if you choose browser testing.
If the required package is missing, run %pip install fastapi==0.162.0 httpx==0.28.1 in a Colab or Jupyter code cell.
Topics covered
A running server does not imply correct request handling. First test paths, missing inputs, and safe responses.
Overall workflow
HTTP request → parameter validation → sensor query → JSON and status code
Request–validation–query–response
An HTTP API receives a request path and parameters, validates values, and returns data. Responses to invalid formats, invalid intervals, and nonexistent paths are part of its contract with users, as is normal JSON.
Check with small requests
FastAPI's TestClient reproduces requests without exposing a network server. Format validation failures, nonexistent paths, and empty query results are different situations.
Separating storage logic into a function lets you reuse the same rules across different paths.
Worked example
The FastAPI /readings path accepts device, start, and end. TestClient sends requests without starting an actual server.
from fastapi import FastAPI,HTTPException
from fastapi.testclient import TestClient
app=FastAPI()
readings=[{'device':'m1','time_s':0.,'value':20.},{'device':'m1','time_s':1.,'value':21.}]
@app.get('/readings')
def get_readings(device:str,start:float=0,end:float=10):
if start>end:raise HTTPException(status_code=400,detail='start must not exceed end')
return [row for row in readings if row['device']==device and start<=row['time_s']<=end]
client=TestClient(app)
for query in ['/readings?device=m1','/readings?device=m1&start=2&end=1']:
result=client.get(query);print(result.status_code,result.json())
200 [{'device': 'm1', 'time_s': 0.0, 'value': 20.0}, {'device': 'm1', 'time_s': 1.0, 'value': 21.0}]
400 {'detail': 'start must not exceed end'}
Official documentation and data
Reference example
View more examples