Week 2
Getting Started
Join the github classroom assignment with the following link:
Once you join your repository will be created https://github.com/blueprint-learn/week2-techteam-sp26-{github-username}
Once you join, GitHub Classroom will automatically create your personal repository. You will getreceive an email withconfirming accessaccess.
After yourreceiving repoaccess:
-
Clone your
reporepository locally -
Install dependencies
-
Run the starter FastAPI app
This repository contains the scaffolding you will extend during this week.
git clone https://github.com/blueprint-learn/week1-techteam-sp26-{github-username}.git
Recap last week
In Week 1, we established the core foundation of APIs using FastAPI. By the end of the session, you had:
-
We builtBuilt a running FastAPI server -
WeCreatedcreatedbasic endpoints -
We usedUsed path parameters -
Verified correctness through automated CI
tested our API contracttests
You also saw how an API defines a contract between a client and a server, and how tests enforce that contract.
Goal for today
will safely accept data from clients.By the end of
today,this week, you will understand how APIs receive structured data and how FastAPI automatically validates incoming data.This is a major step forward: your API will no longer only return data — it
automatically.
Big idea
Last week:week, the interaction pattern was:
Client asks for data → Server returns data
This week:week, we expand that model:
Client sends data → Server validates and accepts data
This shift introduces one of the most important responsibilities of a backend API: validating inputs at the system boundary.
1. How Data Enters an API
There are three mainprimary ways data reaches an API:API endpoint. Understanding these channels is essential for designing correct APIs.
Path parameters
/items/5Query parameters
/items?limit=10Request body (JSON)
{
"name": "Notebook",
"price": 5.99
}
|
Type |
Where used |
Example |
|---|---|---|
|
Path |
Identify resource |
/users/3 |
|
Query |
Filter/search |
?limit=10 |
|
Body |
Send data |
POST JSON |
Each serves a different purpose:
-
Path parameters identify
2.which resource -
Query
Parametersparameters refine how to retrieve -
Request bodies provide new data
Path parameters
Path parameters help define a resource. They usually appear after a / . IDs are usually passed as path parameters to identify a resource.
/items/5
Query parameters
Query parameters appear after a ? in the URL and are commonly used for filtering, pagination, or search controls.
Examples to test:
/items?limit=10
@app.get("/items")
def list_items(limit: int = 10):
return {"limit": limit}
ShowFastAPI automatically:
-
/itemsApplies default values when missing -
/items?limit=5Converts types based on type hints -
/items?limit=abcValidates incorrect input
ExplainFor example, if limit is defined as an integer and a string is provided, FastAPI will reject the request before your function executes.
Default valuesType conversionAutomatic validation
Key insightinsight:
FastAPI parses query strings into typed Python values.
3. Request Bodiesbody & JSON(JSON)
Motivation
RealReal-world APIs receivemust accept structured data:data. Common examples include:
-
User signup information
-
Orders or transactions
-
Messages or posts
-
PaymentsPayment details
ExampleClients send this data as JSON in the request body.
{
"name": "Notebook",
"price": 5.99
}
Naive version
@app.post("/items")
def create_item(item: dict):
return item
ProblemA naive implementation might accept this as a generic dictionary. However, this approach has critical problems:
-
No validation
-
No defined structure
-
No guarantees about data shape
TransitionThis leads to unstable and unsafe APIs
We need a schemaschema.
4. Pydantic Models
FastAPI uses Pydantic models to define structured request bodies.
A Pydantic model specifies:
-
Required fields
-
Types
-
Optional fields
-
Validation rules
When used in an endpoint, FastAPI:
-
Parses incoming JSON
-
Validates types and structure
-
Converts into a Python object
-
Rejects invalid requests automatically
This provides:
-
Schema definition
-
Type enforcement
-
Automatic parsing
-
Validation
The model becomes the contract for accepted data.
Why Validation Matters
Validation at the API boundary protects the system from invalid or malicious input.
Without validation, systems risk:
-
Database corruption
-
Runtime crashes
-
Security vulnerabilities
-
Inconsistent data
With validation, APIs ensure:
-
Safe inputs
-
Predictable structure
-
Stable behavior
Core principle:
Validation is defensive programming at the API boundary.
Define
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
Use
@app.post("/items")
def create_item(item: Item):
return item
Explain
-
Schema definition
-
Type enforcement
-
Automatic parsing
-
Validation