uvicorn: running the API on a real server
TestClient called the app from inside Python. uvicorn runs it as a server on a port, so any program on the machine, in any language, can send it requests.
Use health.py from lesson 4. In a terminal inside the project folder:
uvicorn health:app --port 8100 &
sleep 2
curl -s localhost:8100/health
echo
curl -s localhost:8100/status
echo
kill %1health:app means the app object in health.py. --port 8100 is the door it listens on. The & starts it in the background so the same terminal can keep going; normally you would leave uvicorn running in its own terminal and use a second one.
curl is a command that sends HTTP requests, available on macOS, Linux and Windows 10 and later. echo only adds a line break, and kill %1 stops the background server.
Read the INFO lines. The first four are uvicorn starting. Each request then gets one line: who asked, the method and path, and the status sent back. When something goes wrong on a server, this log is the first place to look.
Sending JSON with curl
uvicorn tickets:app --port 8100 --log-level warning &
sleep 2
curl -s -X POST localhost:8100/tickets \
-H "Content-Type: application/json" \
-d '{"customer": "Asha", "text": "I was charged twice"}'
echo
kill %1-X POST sets the method, -H adds a header, and -d is the body. A backslash at the end of a line continues the command on the next. --log-level warning hides the INFO lines.
The documentation page
While uvicorn is running, open http://localhost:8100/docs in a browser. FastAPI serves an interactive page built from the OpenAPI description in lesson 7, with a Try it out button on every endpoint. Anyone given your service's address can read how to call it there.
& and kill. Stop uvicorn with Ctrl+C.- Start
uvicorn health:app --port 8100 --reloadin its own terminal, change the health message, and call it again without restarting. - Open
/docsand send a POST from the Try it out button. - Call
curl -s localhost:8100/openapi.json.
Slow is fine. Stopping is the only problem.