Tie it all together — build a small JSON API with FastAPI using type hints for validation, path and query parameters, and request bodies.
Why: a web framework turns your Python functions into a web API that other programs and websites can call. FastAPI is a popular modern choice: it uses the type hints you already learned to validate incoming data and to generate interactive docs automatically.
Install FastAPI and the server that runs it:
pip install "fastapi[standard]"Why: a path operation maps a URL to a function. The @app.get decorator says "when someone visits this URL, run this function". Returning a dict sends it back as JSON.
# file: main.py
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def home():
return {'message': 'Hello, API!'}Why: type hints on parameters tell FastAPI how to read the URL. A name in the path ({item_id}) becomes a path parameter; extra function arguments become query parameters (?limit=10). FastAPI validates and converts them for you.
# file: main.py
from fastapi import FastAPI
app = FastAPI()
@app.get('/items/{item_id}')
def get_item(item_id: int, q: str | None = None):
# /items/5?q=shoes -> item_id is the int 5, q is "shoes"
return {'item_id': item_id, 'q': q}Why: for data sent in a POST request, you describe its shape with a Pydantic model — a class of typed fields. FastAPI validates the incoming JSON against it and rejects bad data automatically, before your code runs.
# file: main.py
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
in_stock: bool = True # optional, defaults to True
@app.post('/items')
def create_item(item: Item):
# FastAPI has already validated the JSON into an Item object
return {'created': item.name, 'price': item.price}Why: seeing the code is not enough — here is the full loop to run the API and actually see results. With your virtual environment active and FastAPI installed.
Start the server (press Ctrl+C to stop it):
fastapi dev main.pyWhy: the easiest way to test a GET endpoint is to open its URL. For anything more — including POST endpoints — open /docs: FastAPI builds an interactive page from your code where you click "Try it out", fill in any fields, and hit Execute to see the live response. No extra tools needed.
Open these in your browser while the server runs:
http://127.0.0.1:8000 -> {"message":"Hello, API!"}
http://127.0.0.1:8000/items/5?q=shoes
http://127.0.0.1:8000/docs -> interactive UI to test every endpoint