SlideShare a Scribd company logo
Project Structure &
FastAPI
Introduction
Judul Agenda Bootcamp
Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
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
Python Project File
models/user.py
utils/helper.py
main.py
requirements.txt
Virtual Environment (venv)
Create Virtual Environment Activate Virtual Environment Install Library
Deactivate
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
Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
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:
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":
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
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
Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
Code Snippet:
Quick Start
Key Points:
Simple app creation with minimal code Use
uvicorn main:app --reload to run the app
from fastapi import FastAPI
app = FastAPI()
@app.get("/") def
read_root():
return {"message": "Hello, FastAPI!"}
Path Parameters
@app.get("/items/{item_id}") def
read_item(item_id: int):
return {"item_id": item_id}
You can declare path parameters in your endpoint. They’re passed as arguments:
Here, item_id is a path parameter and is automatically converted to int.
Query Parameters
@app.get("/items/")
def read_item(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
Query parameters are automatically parsed:
You can access them via ?skip=0&limit=10 in the URL.
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.
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
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:
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
Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
● Modularisasi FastAPI dan Error Handling
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.
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:
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/
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.
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..
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).
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.
Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
● Modularisasi FastAPI dan Error Handling
● Middleware
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
Exercise
1. Middleware Log Waktu Request
Buat middleware yang mencatat waktu eksekusi setiap request.
Tampilkan log di terminal dalam format:
bash
CopyEdit
Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
● Modularisasi FastAPI dan Error Handling
● Middleware
● Integrasi Database
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
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
Integrasi Database
3. Buat Tabel (Schema)
Tabel akan dibuat saat aplikasi dijalankan pertama kali.
Integrasi Database
4. Fungsi Helper untuk Query
Supaya tidak copy-paste query, kita buat fungsi:
Integrasi Database
5. CRUD Endpoint
Integrasi Database
5. CRUD Endpoint
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.
Outline
● Project Structure
● Type Hinting
● Introduction to FastAPI
● Modularisasi FastAPI dan Error Handling
● Middleware
● Integrasi Databse
● Mini Project
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
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
Terimakas
ih
Dank
e
Gracia
s
Thank
you
Grazie
Arigat
ou
Merc
i
Syukro
n
Obriga
do
Gamsa
Hamnida
Xie-
Xie
Kheilil
Mamnun

More Related Content

PPT
Slide struktur codeigneter
ODP
Workshop SuBali - CodeIgniter
PDF
Jamal aplikasicrud
PPTX
Laravel Basic Development
PDF
Tutorial ci
DOCX
Tutorial pembuatan REST Service pada Support System menggunakan Servlet dan GSON
PDF
Octav android mysql
PDF
Yii2 fundamentals bagian 1
Slide struktur codeigneter
Workshop SuBali - CodeIgniter
Jamal aplikasicrud
Laravel Basic Development
Tutorial ci
Tutorial pembuatan REST Service pada Support System menggunakan Servlet dan GSON
Octav android mysql
Yii2 fundamentals bagian 1

Similar to Introduction FastAPI for Professional and Student (20)

PDF
Modul 05 Framework CodeIgniter.pdf
PDF
Tutorial ci
PDF
Belajar Framework CodeIgnitier Lengkap (bahasa Indonesia)
PDF
Modul pelatihan-django-dasar-possupi-v1
PDF
Tutorial Aplikasi android client server menggunakan REST API Django
DOCX
Belajar framework code igniter xii rpl
PDF
Belajar php-dengan-framework-code-igniter1
PDF
Mudafiq converter suhucorba
PDF
Membuat Catatan Online dengan Cherrypy
PDF
Belajar php dengan framework code igniter3
PDF
Belajar php-dengan-framework-code-igniter
PDF
Php dgn framework code ignitier
PDF
Php dgn frame work code ignitier
PDF
Belajar php-dengan-framework-code-igniter
PDF
Jeni Web Programming Bab 2 Basic Servlets
PPTX
Tugas 3 – 0317 (individu)
DOCX
E commerce dengan php mysql
PPTX
Codeigniter lanjut helper dan library
PDF
web_server-side-scripting2.pdf
PPTX
Fundamental Django, dan Contoh Program CRUD Katalog Buku Perpustakaan.
Modul 05 Framework CodeIgniter.pdf
Tutorial ci
Belajar Framework CodeIgnitier Lengkap (bahasa Indonesia)
Modul pelatihan-django-dasar-possupi-v1
Tutorial Aplikasi android client server menggunakan REST API Django
Belajar framework code igniter xii rpl
Belajar php-dengan-framework-code-igniter1
Mudafiq converter suhucorba
Membuat Catatan Online dengan Cherrypy
Belajar php dengan framework code igniter3
Belajar php-dengan-framework-code-igniter
Php dgn framework code ignitier
Php dgn frame work code ignitier
Belajar php-dengan-framework-code-igniter
Jeni Web Programming Bab 2 Basic Servlets
Tugas 3 – 0317 (individu)
E commerce dengan php mysql
Codeigniter lanjut helper dan library
web_server-side-scripting2.pdf
Fundamental Django, dan Contoh Program CRUD Katalog Buku Perpustakaan.
Ad

Recently uploaded (12)

PPTX
Gagal Ginjal Akut GHINA SELVIRA .pptx
PDF
GERUDUK MJKN aplikasi mobile JKN persentation
PDF
6754aa176b39b (1).pdf data analisis acara
PDF
Llama Implementations from Scratch - Avalon AI.pdf
PPTX
PPT Kelas 10. Teks Hasil Observasi (Minggu 1).pptx
PPTX
Paper sirosis hepatis dr siti taqwa.jdusp
PDF
SLOT 2 Slide Presentation PELAKSANAAN EKSA ILKBS oleh Ts Dr Loke.pdf
PPTX
PRESNTASI pembangunan perumahan komersil dua lantai
PDF
LK - SIMULASI SIKLUS INKUIRI KOLABORATIF.pdf
PPTX
Dokter):6:’syaksudysnnwysydyejeushx bshske ueie
PPTX
EFEKTIVITAS EKSTRAK DAUN INDIGOFERA.pptx
PPTX
OK PENGARUH MARKETING MIX TERHADAP RECOMMENDATION INTENTION DAN REPURCHASE IN...
Gagal Ginjal Akut GHINA SELVIRA .pptx
GERUDUK MJKN aplikasi mobile JKN persentation
6754aa176b39b (1).pdf data analisis acara
Llama Implementations from Scratch - Avalon AI.pdf
PPT Kelas 10. Teks Hasil Observasi (Minggu 1).pptx
Paper sirosis hepatis dr siti taqwa.jdusp
SLOT 2 Slide Presentation PELAKSANAAN EKSA ILKBS oleh Ts Dr Loke.pdf
PRESNTASI pembangunan perumahan komersil dua lantai
LK - SIMULASI SIKLUS INKUIRI KOLABORATIF.pdf
Dokter):6:’syaksudysnnwysydyejeushx bshske ueie
EFEKTIVITAS EKSTRAK DAUN INDIGOFERA.pptx
OK PENGARUH MARKETING MIX TERHADAP RECOMMENDATION INTENTION DAN REPURCHASE IN...
Ad

Introduction FastAPI for Professional and Student

  • 2. Outline ● Project Structure ● Type Hinting ● Introduction to FastAPI
  • 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
  • 5. Virtual Environment (venv) Create Virtual Environment Activate Virtual Environment Install Library Deactivate
  • 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
  • 7. Outline ● Project Structure ● Type Hinting ● Introduction to FastAPI
  • 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
  • 12. Outline ● Project Structure ● Type Hinting ● Introduction to FastAPI
  • 13. Code Snippet: Quick Start Key Points: Simple app creation with minimal code Use uvicorn main:app --reload to run the app from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"message": "Hello, FastAPI!"}
  • 14. Path Parameters @app.get("/items/{item_id}") def read_item(item_id: int): return {"item_id": item_id} You can declare path parameters in your endpoint. They’re passed as arguments: Here, item_id is a path parameter and is automatically converted to int.
  • 15. Query Parameters @app.get("/items/") def read_item(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit} Query parameters are automatically parsed: You can access them via ?skip=0&limit=10 in the URL.
  • 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
  • 20. Outline ● Project Structure ● Type Hinting ● Introduction to FastAPI ● Modularisasi FastAPI dan Error Handling
  • 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
  • 34. Integrasi Database 3. Buat Tabel (Schema) Tabel akan dibuat saat aplikasi dijalankan pertama kali.
  • 35. Integrasi Database 4. Fungsi Helper untuk Query Supaya tidak copy-paste query, kita buat fungsi:
  • 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