Course materials · Microprocessor Applications

An HTTP API for sensor data

English translation

A running server does not imply correct request handling. First test paths, missing inputs, and safe responses.

Before practice

01 Can you test requests before starting the server?

Description

TestClient lets you check paths, parameters, and responses without exposing an actual HTTP server.

02 How do you distinguish a nonexistent device from a nonexistent path?

Description

Use different response rules for empty query results and nonexistent API paths.

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.

Practice

Preview practice notebookDownload practice notebook

1. Test requests through function calls

Starting conditions

The FastAPI /readings path accepts device, start, and end. TestClient sends requests without starting an actual server.

Procedure

  1. Execute the provided valid request and check the status code and JSON fields.
  2. Execute a start>end request and distinguish it from a normal response.

Results to retain

Items to record and points to check
Request
Status code
Key JSON fields

Points to check

  • Did you distinguish the roles of HTML pages and JSON APIs?
  • Did you check the request flow without exposing the server externally?

2. Distinguish invalid requests

Starting conditions

Test a missing device, start=abc, nonexistent device m9, and nonexistent path /unknown.

Procedure

  1. Tabulate the status codes and response bodies for the four requests.
  2. Decide which situation to handle as an empty list: absent data or an invalid request.
  3. Use asserts to fix two valid and invalid request cases for checking after later changes.

Results to retain

Items to record and points to check
Request
Status code
Meaning
Client's next action

Points to check

  • Did you distinguish 422 input validation from 404 path errors?
  • Is the error body free of sensitive server internals?

3. The storage integration boundary

Starting conditions

You want to call the SQLite query function from the previous unit inside the API.

Procedure

  1. Mark where to replace reading from a temporary list with a storage function call.
  2. Separate API input validation from DB query responsibilities.
  3. Check whether one response identifies the device, time, and unit clearly enough for a user to interpret it.

Results to retain

Items to record and points to check
Components
Received input
Return value
Failure handling

Points to check

  • Did you avoid copying the query logic into each path?
  • Can you reproduce the same request with TestClient before connecting external devices?

Official examples and data