APIs for AIFastAPI 0.141 · httpx2 2.13 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
19 small wins to finish your pathNext lesson

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.

Examplehealth.py
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

Example
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 or httpx2
FastAPI's testing page says to install 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

Example
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.

Try it yourself
  • Add a GET /version endpoint that returns {"version": "1.0"}, and call it.
  • Return a list instead of a dictionary from health.
  • Change @app.get to @app.post and call it with client.post.

This is what real progress feels like.