Setelah sebelumnya kita belajar bikin REST API pake Node.js dan Golang, sekarang kita akan coba bikin REST API dengan Python menggunakan FastAPI. Framework ini dipilih karena performanya yang cepat, modern, dan punya fitur auto-documentation yang keren!
Persiapan
- Python 3.7+ terinstall
- Code editor (VS Code recommended + Python extension)
- Postman untuk testing API
- Basic knowledge Python
1. Setup Project
Pertama, kita bikin virtual environment dan install dependencies yang dibutuhkan:
# Bikin folder project
mkdir python-rest-api
cd python-rest-api
# Bikin virtual environment
python -m venv venv
# Aktivasi virtual environment
# Windows
venv\Scripts\activate
# Linux/Mac
source venv/bin/activate
# Install dependencies
pip install fastapi uvicorn pydantic
2. Struktur Project
python-rest-api/
├── venv/
├── app/
│ ├── __init__.py
│ ├── main.py
│ └── models.py
└── requirements.txt
3. Bikin Model dengan Pydantic
Buat file app/models.py
:
from pydantic import BaseModel
class Book(BaseModel):
id: int
title: str
author: str
class BookCreate(BaseModel):
title: str
author: str
4. Implementasi Main Server
Buat file app/main.py
:
from fastapi import FastAPI, HTTPException
from typing import List
from .models import Book, BookCreate
app = FastAPI(
title="Book API",
description="Simple REST API for managing books",
version="1.0.0"
)
# Simulasi database dengan list
books = [
Book(id=1, title="Harry Potter", author="J.K. Rowling"),
Book(id=2, title="Lord of the Rings", author="J.R.R. Tolkien")
]
5. Implementasi CRUD Endpoints
GET - Ambil Semua Buku
@app.get("/books/", response_model=List[Book])
async def get_books():
return books
GET - Ambil Buku by ID
@app.get("/books/{book_id}", response_model=Book)
async def get_book(book_id: int):
book = next((book for book in books if book.id == book_id), None)
if book is None:
raise HTTPException(status_code=404, detail="Book not found")
return book
POST - Tambah Buku Baru
@app.post("/books/", response_model=Book, status_code=201)
async def create_book(book: BookCreate):
new_book = Book(
id=len(books) + 1,
title=book.title,
author=book.author
)
books.append(new_book)
return new_book
PUT - Update Buku
@app.put("/books/{book_id}", response_model=Book)
async def update_book(book_id: int, book_update: BookCreate):
book_idx = next((idx for idx, book in enumerate(books) if book.id == book_id), None)
if book_idx is None:
raise HTTPException(status_code=404, detail="Book not found")
updated_book = Book(
id=book_id,
title=book_update.title,
author=book_update.author
)
books[book_idx] = updated_book
return updated_book
DELETE - Hapus Buku
@app.delete("/books/{book_id}", status_code=204)
async def delete_book(book_id: int):
book_idx = next((idx for idx, book in enumerate(books) if book.id == book_id), None)
if book_idx is None:
raise HTTPException(status_code=404, detail="Book not found")
books.pop(book_idx)
return None
6. Jalankan Server
Untuk menjalankan server, gunakan command:
uvicorn app.main:app --reload
7. Auto-Generated Documentation
FastAPI secara otomatis menyediakan dokumentasi API yang interaktif:
- Swagger UI:
http://localhost:8000/docs
- ReDoc:
http://localhost:8000/redoc
8. Testing dengan Postman
GET All Books
GET http://localhost:8000/books/
POST New Book
POST http://localhost:8000/books/
Body:
{ "title": "The Hobbit", "author": "J.R.R. Tolkien" }
Kenapa FastAPI?
- Performance yang sangat cepat (setara dengan Node.js dan Go)
- Auto-generated API documentation
- Modern Python type hints
- Built-in data validation
- Async support
9. Pengembangan Lebih Lanjut
Database Integration
Integrasi dengan SQLAlchemy + PostgreSQL
Authentication
Implement JWT authentication
Caching
Implement Redis untuk caching
Testing
Unit testing dengan pytest
Tips Performance
- Gunakan async/await untuk operasi I/O
- Implement caching untuk data yang sering diakses
- Gunakan connection pooling untuk database
- Enable CORS hanya untuk domain yang diperlukan
10. Error Handling
from fastapi import HTTPException
# Custom exception handler
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={"message": exc.detail}
)
Troubleshooting
ModuleNotFoundError
Pastikan semua dependencies terinstall dengan pip install -r requirements.txt
Address already in use
Ganti port dengan uvicorn app.main:app --port 8001
Challenge!
Coba tambahkan fitur-fitur berikut:
- Implement search dan filter endpoint
- Tambahkan pagination
- Implement file upload untuk cover buku
- Bikin rate limiting middleware
Requirements.txt
fastapi==0.68.0 uvicorn==0.15.0 pydantic==1.8.2