0% found this document useful (0 votes)
2 views5 pages

FastAPI Session2 Notes

Uploaded by

kamandamulwa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

FastAPI Session2 Notes

Uploaded by

kamandamulwa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Session 2 -Sending Data & Building CRUD

What This Session Covers


In Session 1, our API could only read and return data. In this session, you will learn how an API
receives data sent TO it -through the request body -and how to validate that data using Pydantic
models. By the end, you will build a complete CRUD API: Create, Read, Update, and Delete
records, just like a real backend system.

1. The Four Verbs of CRUD

CRUD Action HTTP Method FastAPI Decorator Real-World Example


Create POST @[Link](...) Admit a new student
Read GET @[Link](...) Look up a student's record
Update PUT @[Link](...) Correct a student's name
Delete DELETE @[Link](...) Remove a withdrawn student

2. The Request Body -Sending Data IN


URLs have limits -they cannot hold large or complex data, like a whole student record with a
name, age, and course. For that, we use a request body- a parcel of data sent along with the
request, separate from the URL.

3. Pydantic -Describing Your Data's Shape


 Pydantic is a library that comes installed with FastAPI.
 It lets you describe exactly what a piece of data should look like -which fields it has, and
what type each field must be.
 FastAPI then uses this description to automatically validate every request body that
arrives.
define a model for a student:

• class Student(BaseModel): -we create a new class, the same 'class' keyword style you
may have briefly seen before. BaseModel is borrowed from Pydantic and gives our class
its validation powers
• Each line below is a field name followed by its required type -exactly like the type hints
from Session 1, just describing a whole record instead of a single value
• is_sponsored: bool = False -this field has a default value, making it optional. If the
request body does not include it, FastAPI assumes False

4. CREATE -Building Our First POST Route


Let's build a simple in-memory "database" -just a Python list -and a route that adds a new
student to it.

• student: Student -this parameter is not in the URL, and its type is our Pydantic model,
not a simple str or int. FastAPI ecognizes this and automatically reads it from the request
body, validating every field as it does
• [Link](student) -we add the new student object onto our list, the
same .append() method you already know from Session 5
On the /docs page, try sending this as your request body:

{
"name": "Brian Otieno",
"age": 22,
"course": "Data Engineering"
}

Expected output:
{
"message": "Student added successfully",
"data": {
"name": "Brian Otieno",
"age": 22,
"course": "Data Engineering",
"is_sponsored": false
}
}

Notice that is_sponsored appeared automatically with its default value, even though we never
sent it. Now try sending age as "twenty-two" instead of 22 -Pydantic rejects it immediately,
before create_student() even runs, the same automatic protection we saw with type hints in
Session 1.

5. READ -Listing and Finding Students


We already know GET routes from Session 1. Let's use them to read our growing list of
students.
we are simply using the student's position in the list (its index) as a stand-in ID. This is a
simplification for learning

6. UPDATE -Changing an Existing Record


To update a record, we combine what we have learned: a path parameter to identify WHICH
record, and a request body to say WHAT it should become.

How FastAPI tells them apart: student_id: int comes from the URL path
("/students/{student_id}"), so FastAPI reads it from there. updated_student: Student is a
Pydantic model, so FastAPI knows to read it from the request body instead. FastAPI
decides where each parameter comes from based on its name (does it match something in
the path?) and its type (is it a Pydantic model?) -not the order you write them in.

7. DELETE -Removing a Record

.pop(student_id) removes the item at that position from the list and gives it back to us

8. The Complete Picture -Full CRUD Together


Here is the entire mini student-records API in one place, exactly as it would appear in [Link]:

from fastapi import FastAPI


from pydantic import BaseModel
app = FastAPI()
students = []

class Student(BaseModel):
name: str
age: int
course: str
is_sponsored: bool = False

@[Link]("/students")
def create_student(student: Student):
[Link](student)
return {"message": "Student added", "data": student}

@[Link]("/students")
def get_all_students():
return students

@[Link]("/students/{student_id}")
def get_student(student_id: int):
return students[student_id]

@[Link]("/students/{student_id}")
def update_student(student_id: int, updated_student: Student):
students[student_id] = updated_student
return {"message": "Student updated", "data": updated_student}

@[Link]("/students/{student_id}")
def delete_student(student_id: int):
removed = [Link](student_id)
return {"message": "Student removed", "data": removed}

You might also like