FastAPI: your first endpoint
Part 1 faked the server. FastAPI builds a real one: you write ordinary Python functions and say which URL each one answers.
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health():
return {"status": "ok"}app = FastAPI() makes the application. @app.get("/health") is a decorator saying: when a GET request arrives for /health, run the function below. A function connected to a URL like this is an endpoint.
The function returns a dictionary and FastAPI sends it as JSON. /health is a common first endpoint: other systems call it to check the service is up.
Calling it
from fastapi.testclient import TestClient
from health import app
client = TestClient(app)
response = client.get("/health")
print(response.status_code)
print(response.json())TestClient is an httpx2.Client whose transport hands each request straight to your app, the way MockTransport handed it to a function in lesson 3. Your app does not know the difference, and no server has to be started. Lesson 8 runs the same app on a real server.
httpx. The Starlette version FastAPI 0.141 installs warns that httpx is deprecated for its test client and asks for httpx2, the continuation of httpx maintained by Pydantic. The two have the same API; older code you read will say import httpx.A URL nobody wrote
print(client.get("/status").status_code)
print(client.get("/status").json())
print(client.post("/health").status_code)A path with no endpoint is 404. A path that exists, called with the wrong method, is 405, method not allowed. FastAPI sends both for you.
- Add a
GET /versionendpoint that returns{"version": "1.0"}, and call it. - Return a list instead of a dictionary from
health. - Change
@app.getto@app.postand call it withclient.post.
This is what real progress feels like.