3. Typical Python Project Structure
main.py: Entry point of the application
utils.py: Contains helper functions
models/: Directory to organize model-related code
__init__.py: Marks a directory as a Python package
Importing Across Modules
6. Exercise
● Create a models/ and utils/ folder inside your project directory.
● Move the Customer class into a new file:
• models/customer_model.py
● Move the welcome_message function into a new file:
• utils/message_utils.py
● In your main.py:
• Import and use the Customer class from models/customer_model.py
• Import and use the welcome_message function from utils/message_utils.py
● Create and activate a virtual environment
● Install FastAPI using pip
8. Type Hinting
Python has support for optional "type hints" (also
called "type annotations").
These "type hints" or annotations are a special
syntax that allow declaring the type of a variable. By
declaring types for your variables, editors and tools
can give you better support.
Example:
def get_full_name(first_name, last_name):
full_name = first_name.title() + " " + last_name.title()
return full_name
print(get_full_name("john", "doe"))
Output
It's a very simple program.But now imagine that you were writing it from
scratch. At some point you would have started the definition of the
function, you had the parameters ready...
But then you have to call "that method that converts the first letter to
upper case".
Was it upper? Was it uppercase? first_uppercase? capitalize?
Then, you try with the old programmer's friend, editor autocompletion.
You type the first parameter of the function, first_name, then a dot (.)
and then hit Ctrl+Space to trigger the completion.
But, sadly, you get nothing useful:
9. Type Hinting (Cont)
Let's modify a single line from the previous version.
We will change exactly this fragment, the
parameters of the function, from:
first_name, last_name
to
first_name: str, last_name: str
def full_name = first_name.title() + " " + last_name.title()
return full_name
print(get_full_name("john", "doe"))
At the same point, you try to trigger the autocomplete with
Ctrl+Space and you see:
With that, you can scroll, seeing the
options, until you find the one that
"rings a bell":
10. Type Hinting (Cont)
Check this function, it already has type hints:
def get_name_with_age(name: str, age: int):
name_with_age = name + " is this old: " + age
return name_with_age
Because the editor knows the types of the variables,
you don't only get completion, you also get error
checks:
Now you know that you have to fix it, convert age to a string
with str(age):
def get_name_with_age(name: str, age: int):
name_with_age = name + " is this old: " + str(age)
return name_with_age
11. Exercise
Please redeclared this function using type hinting:
def fillerup(items_names,items_weights,capacity):
output = []
total_weight = 0
i = 0
while i < len(items_names) and total_weight + items_weights[i] <= capacity:
output.append(items_names[i])
total_weight += items_weights[i]
i+=1
return output
16. Data Validation with Pydantic
from pydantic import BaseModel
class Item(BaseModel): name: str
price: float
@app.post("/items/")
def create_item(item: Item):
return {"name": item.name, "price": item.price}
FastAPI uses Pydantic models to validate request data and define schemas:
Pydantic automatically validates the input and converts types.
17. ReDoc: /redoc
Automatic API Documentation
Swagger UI: /docs
FastAPI automatically generates interactive API documentation using Swagger UI and
ReDoc.
SwaggerUI - http://127.0.0.1:8000/docs
ReDoc - http://127.0.0.1:8000/redoc
18. Asynchronous Support
@app.get("/async_items/") async def
read_async_item():
return {"message": "This is asynchronous"}
FastAPI is asynchronous by nature, which means you can define async functions to
handle requests efficiently:
19. Exercise
● Create a User model using Pydantic
● Implement:
○ POST /users to add user to an in-memory list
○ GET /users to return the full list of users
21. Request Body dan Response Model
Menggunakan Pydantic Model untuk Input/Output
● Pydantic digunakan untuk membuat model data yang memvalidasi input secara
otomatis.
● Model ini akan digunakan sebagai:
○ Request Body: format data yang diterima API.
○ Response Model: format data yang dikirim kembali ke client.
Validasi Otomatis FastAPI
● FastAPI akan otomatis memeriksa tipe data sesuai Pydantic model.
● Jika data tidak sesuai, FastAPI akan mengembalikan error 422 dengan pesan validasi.
Response Model dan Status Code
● response_model digunakan untuk mendefinisikan format keluaran API.
● status_code digunakan untuk menentukan kode HTTP, misalnya 201 Created untuk
data baru.
ProductCreate → model untuk data input.
ProductResponse → model untuk data output.
Jika input salah tipe (misalnya harga string), FastAPI otomatis
balas error validasi.
22. FastAPI Project Structure
Struktur proyek yang modular memudahkan
pengelolaan kode: 1. main.py
● File entry point aplikasi FastAPI.
● Di sini kita mendaftarkan semua router dari folder
routers/.
● Fungsi: Menginisialisasi aplikasi dan menggabungkan
semua router.
Contoh isi:
23. FastAPI Project Structure
Struktur proyek yang modular memudahkan
pengelolaan kode: 2. Folder routers/
Tempat menyimpan semua route handler (endpoint API).
● Setiap file .py di sini biasanya untuk satu fitur atau resource
(misal: user_router.py, product_router.py).
● __init__.py → membuat folder ini dianggap Python
package, sehingga bisa diimport.
● user_router.py → berisi definisi endpoint untuk resource
User.
● Fungsi: Mengatur URL path dan HTTP method, lalu
memanggil fungsi dari services/
24. FastAPI Project Structure
Struktur proyek yang modular memudahkan
pengelolaan kode: 3. Folder schemas/
Tempat menyimpan Pydantic models untuk validasi request dan
format response.
● user_schema.py → mendefinisikan struktur data
UserCreate (input) dan UserResponse (output).
● __init__.py → menjadikan folder ini package Python.
Fungsi: Memastikan data masuk/keluar sesuai format dan
tervalidasi otomatis.
25. FastAPI Project Structure
Struktur proyek yang modular memudahkan
pengelolaan kode: 4. Folder services/
Tempat menyimpan logika bisnis (business logic) dan operasi
data.
● user_service.py → berisi fungsi membuat user baru, cek
email unik, dll.
● __init__.py → menjadikan folder ini package
● Fungsi: Memisahkan logika pemrosesan data dari route
agar lebih rapi dan mudah diuji..
26. FastAPI Project Structure
Struktur proyek yang modular memudahkan
pengelolaan kode: 5. requirements.txt
● Berisi daftar library yang diperlukan untuk
menjalankan proyek.
● Fungsi: Memudahkan instalasi dependency (pip
install -r requirements.txt).
27. Exercise
1. Refactor API user ke struktur modular seperti contoh di atas.
2. Tambahkan validasi:
● Email unik
● Nama minimal 3 karakter
1. Gunakan HTTPException untuk mengembalikan pesan error yang sesuai.
2. Uji coba API menggunakan FastAPI docs di http://127.0.0.1:8000/docs.
28. Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
● Modularisasi FastAPI dan Error Handling
● Middleware
29. Middleware
Middleware adalah lapisan perantara yang dijalankan sebelum dan sesudah request
diproses oleh endpoint.
Tujuan utama:
● Logging request/response
● Authentication global
● Modifikasi request atau response
● Menangani CORS, rate limiting, dll.
Alurnya:
@app.middleware("http") akan membungkus semua request HTTP.
call_next(request) adalah cara memanggil proses berikutnya (termasuk endpoint).
Middleware bisa:
● Menambah log
● Mengubah request/response
● Menolak request tertentu
30. Exercise
1. Middleware Log Waktu Request
Buat middleware yang mencatat waktu eksekusi setiap request.
Tampilkan log di terminal dalam format:
bash
CopyEdit
31. Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
● Modularisasi FastAPI dan Error Handling
● Middleware
● Integrasi Database
32. Integrasi Database
Menghubungkan aplikasi FastAPI dengan database SQLite secara asynchronous menggunakan SQLModel (built di atas SQLAlchemy).
Konsep Dasar
1. SQLite
○ Database ringan, berbasis file (.db), cocok untuk prototyping.
○ Tidak memerlukan server terpisah.
2. Async Database Access
○ Dengan aiosqlite, kita bisa menjalankan query SQL secara asynchronous.
○ Tidak perlu ORM, kita langsung kirim perintah SQL.
3. CRUD
CRUD adalah singkatan dari:
○ Create → Menambah data ke tabel
○ Read → Mengambil data dari tabel
○ Update → Mengubah data yang sudah ada
○ Delete → Menghapus data
33. Integrasi Database
1. Install Library
Kita pakai:
● FastAPI → framework API
● aiosqlite → koneksi SQLite async
● uvicorn → server untuk menjalankan FastAPI
2. Buat Koneksi Database
Kita menggunakan event handler di FastAPI:
● startup → koneksi ke database saat aplikasi mulai
● shutdown → menutup koneksi saat aplikasi berhenti
38. Exercise
1. Jalankan aplikasi di local:
2. Gunakan Swagger UI di http://127.0.0.1:8000/docs.
3. Coba:
● Tambah 3 user.
● Ambil semua user.
● Update salah satu user.
● Hapus salah satu user.
1. Modifikasi kode agar ada pencarian user berdasarkan email.
39. Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
● Modularisasi FastAPI dan Error Handling
● Middleware
● Integrasi Databse
● Mini Project
40. Mini Project
Tujuan:
Menggabungkan seluruh materi sebelumnya dalam sebuah proyek FastAPI yang memiliki endpoint CRUD sederhana untuk catatan keuangan.
1. Spesifikasi API
● Tambah catatan keuangan
Method: POST /catatan
Body: JSON (judul, jumlah, tanggal, kategori)
Validasi: Pydantic
Autentikasi: Header Token
● Lihat semua catatan
Method: GET /catatan
Autentikasi: Header Token
● Lihat catatan berdasarkan ID
Method: GET /catatan/{id}
Autentikasi: Header Token
● Hapus catatan
Method: DELETE /catatan/{id}
Autentikasi: Header Token
41. Mini Project
2. Fitur yang Digunakan
● Pydantic → Validasi input request
● Autentikasi Token Sederhana → Menggunakan X-Token di header
● SQLite (tanpa ORM) → Menggunakan sqlite3 dan query SQL langsung
● CRUD (Create, Read, Delete)
3. Alur Integrasi
1. Setup Database
○ Buat file database.py untuk koneksi dan fungsi eksekusi query
○ Pastikan tabel dibuat jika belum ada
2. Model Pydantic
○ Buat schemas.py untuk mendefinisikan struktur request & response
3. Autentikasi
○ Middleware / Dependency untuk memeriksa token dari header
4. CRUD
○ POST → Insert data ke SQLite
○ GET → Select data dari SQLite
○ DELETE → Hapus data dari SQLite