A REST API exposes your application's data over HTTP: clients use verbs (GET to read, POST to create, PUT/PATCH to update, DELETE to remove) on resource URLs. FastAPI is the modern Python framework for building them, using type hints for automatic validation and docs.
Defining endpoints
Decorate functions with the HTTP verb and path. A Pydantic model validates the request body automatically:
from fastapi import FastAPIfrom pydantic import BaseModelapp = FastAPI()class Student(BaseModel): # defines & validates the request shapename: strpackage: float@app.get("/students")def list_students():return [{"name": "Ana", "package": 7.5}]@app.post("/students")def add(student: Student): # body validated & parsed automaticallyreturn {"created": student.name}@app.get("/students/{sid}") # path parameterdef get_student(sid: int):return {"id": sid}
Running & docs
FastAPI runs on an ASGI server and generates interactive API docs for free:
uvicorn main:app --reload# visit http://localhost:8000/docs for auto-generated interactive docs
Key takeaways
- 01REST exposes resources over HTTP verbs: GET/POST/PUT/PATCH/DELETE.
- 02FastAPI maps decorated functions to routes; path/query params come from parameters.
- 03Pydantic models validate and parse request bodies from type hints.
- 04Invalid requests get automatic, clear error responses.
- 05Run with an ASGI server (uvicorn); interactive docs are generated at /docs.
