Skip to main content
Albero Academy

Building a REST API

Expose your own endpoints with FastAPI.

APIs11 min

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:

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Student(BaseModel): # defines & validates the request shape
name: str
package: float
@app.get("/students")
def list_students():
return [{"name": "Ana", "package": 7.5}]
@app.post("/students")
def add(student: Student): # body validated & parsed automatically
return {"created": student.name}
@app.get("/students/{sid}") # path parameter
def get_student(sid: int):
return {"id": sid}

Running & docs

FastAPI runs on an ASGI server and generates interactive API docs for free:

terminal
uvicorn main:app --reload
# visit http://localhost:8000/docs for auto-generated interactive docs

Key takeaways

  1. 01REST exposes resources over HTTP verbs: GET/POST/PUT/PATCH/DELETE.
  2. 02FastAPI maps decorated functions to routes; path/query params come from parameters.
  3. 03Pydantic models validate and parse request bodies from type hints.
  4. 04Invalid requests get automatic, clear error responses.
  5. 05Run with an ASGI server (uvicorn); interactive docs are generated at /docs.

Finished this chapter?

Mark it complete to track your progress through Python.