강의자료 · 마이크로프로세서응용설계

센서 데이터를 제공하는 HTTP API · 학습

실행 조건

fastapi·httpx가 필요합니다. 브라우저 시험을 선택할 때만 uvicorn을 추가로 사용합니다.

필요한 패키지가 없으면 Colab·Jupyter 코드 셀에서 %pip install fastapi==0.162.0 httpx==0.28.1를 실행하세요.

이번에 배울 내용

서버가 동작한다는 것과 요청을 올바르게 처리한다는 것은 다릅니다. 경로·누락 입력·안전한 응답을 먼저 시험합니다.

전체 흐름

HTTP 요청 → Parameter 검사 → 센서 조회 → JSON·Status code

요청–검증–조회–응답

HTTP API는 요청 경로와 Parameter를 받아 값을 검사하고 데이터를 돌려줍니다. 정상 JSON뿐 아니라 잘못된 형식·잘못된 구간·없는 경로의 응답도 사용자와의 약속입니다.

작은 요청으로 확인하기

FastAPI의 TestClient는 네트워크 서버를 공개하지 않고 요청을 재현합니다. 형식 검증 실패, 없는 경로, 빈 조회 결과는 서로 다른 상황입니다.

저장소 로직은 함수로 분리하면 같은 규칙을 다른 경로에서도 재사용할 수 있습니다.

풀이 예제

FastAPI의 /readings 경로에서 device와 start·end를 받습니다. TestClient는 실제 서버를 켜지 않고 요청을 보냅니다.

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'}

공식 문서·데이터

참고 예제

추가 예제 보기

참고 자료