FastAPI – Dhisidda API-yo Python ah oo Xawaare Dheer
FastAPI waa framework casri ah oo waxqabad sare leh oo loogu talagalay dhisidda API-yada Python. Aad buu u dhaqso badan yahay (isku dhowyahay Node.js iyo Go), si fudud ayaa loo baran karaa, wuxuuna la imanayaa dukumenti API oo toos ah. Aan dhisno API dhammaystiran si aan u aragno sababta horumariyeyaashu u jecel yihiin!
🚀 Maxaa FastAPI ka dhigaya mid gaar ah?
FastAPI waxa uu gilgilay bulshada Python sababo muuqda dartood:
- ⚡ Aad u Dheereeya: Mid ka mid ah framework-yada Python ee ugu degdegga badan
- 🎯 Hubinta Noocyada: Ku dhisan type hints-ka Python si loogu helo xaqiijin toos ah
- 📚 Dukumenti Toos ah: Swagger UI oo si toos ah loo abuuro
- 🔒 Amni: Taageero u leh OAuth2, JWT tokens, iyo in ka badan
- 🎨 Python Casri ah: Waxay adeegsataa async/await si loo farsameeyo hawlo is barbar socda
- ⚙️ Koodh yar: Waxay yaraynaysaa koodhka ku celiska ah ilaa 40%
Isbarbardhigga Waxqabadka
FastAPI waxay la mid tahay Node.js iyo Go:
- FastAPI: ~20,000-30,000 codsi/ilbiriqsi
- Flask: ~3,000-5,000 codsi/ilbiriqsi
- Django: ~2,000-4,000 codsi/ilbiriqsi
📦 Rakibidda & Dejinta
Aan abuurno deegaan dalwadeed oo aan ku rakibno FastAPI:
# Abuur gal mashruuc
mkdir fastapi-blog
cd fastapi-blog
# Abuur deegaan la maamulo
python -m venv venv
# Daar deegaanka
# Linux/Mac:
source venv/bin/activate
# Windows:
# venv\Scripts\activate
# Ku rakib FastAPI iyo Uvicorn (ASGI server)
pip install fastapi uvicorn[standard]
pip install sqlalchemy pydantic-settings python-multipart
🏗️ Qaab-dhismeedka Mashruuca
Abuur qaab nadiif ah oo habaysan:
fastapi-blog/
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── models.py
│ ├── schemas.py
│ ├── database.py
│ └── routers/
│ ├── __init__.py
│ └── posts.py
├── venv/
└── requirements.txt
🎯 Dhisidda Blog API
Aan dhisno API blog ah oo leh hawlgallo CRUD dhammaystiran.
Tallaabada 1: Dejinta Kaydka Xogta
Abuur app/database.py:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# SQLite database
SQLALCHEMY_DATABASE_URL = "sqlite:///./blog.db"
# Create engine
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
# Create session
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Base class for models
Base = declarative_base()
# Dependency to get database session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Tallaabada 2: Model-yada Kaydka Xogta
Abuur app/models.py:
from sqlalchemy import Column, Integer, String, Text, DateTime
from sqlalchemy.sql import func
from app.database import Base
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(200), nullable=False)
content = Column(Text, nullable=False)
author = Column(String(100), nullable=False)
published = Column(Integer, default=1)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
Tallaabada 3: Schemas Pydantic
Abuur app/schemas.py si loo helo xaqiijinta codsiga/jawaabta:
from pydantic import BaseModel, Field
from datetime import datetime
from typing import Optional
# Base schema
class PostBase(BaseModel):
title: str = Field(..., min_length=3, max_length=200)
content: str = Field(..., min_length=10)
author: str = Field(..., min_length=2, max_length=100)
published: int = Field(default=1, ge=0, le=1)
# Schema for creating posts
class PostCreate(PostBase):
pass
# Schema for updating posts
class PostUpdate(BaseModel):
title: Optional[str] = Field(None, min_length=3, max_length=200)
content: Optional[str] = Field(None, min_length=10)
author: Optional[str] = None
published: Optional[int] = Field(None, ge=0, le=1)
# Schema for responses
class PostResponse(PostBase):
id: int
created_at: datetime
updated_at: Optional[datetime]
class Config:
from_attributes = True
💡 Fikrad Muhiim ah: Model-yada Pydantic waxay si toos ah u xaqiijiyaan xogta oo waxay u beddelaan noocyada saxda ah!
Tallaabada 4: Routes-ka API-ga
Abuur app/routers/posts.py:
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app import models, schemas
from app.database import get_db
router = APIRouter(
prefix="/api/posts",
tags=["Posts"]
)
# Get all posts
@router.get("/", response_model=List[schemas.PostResponse])
async def get_posts(
skip: int = 0,
limit: int = 10,
db: Session = Depends(get_db)
):
"""
Retrieve all blog posts with pagination
- **skip**: Number of posts to skip (default: 0)
- **limit**: Maximum number of posts to return (default: 10)
"""
posts = db.query(models.Post).offset(skip).limit(limit).all()
return posts
# Get single post
@router.get("/{post_id}", response_model=schemas.PostResponse)
async def get_post(post_id: int, db: Session = Depends(get_db)):
"""
Retrieve a specific blog post by ID
"""
post = db.query(models.Post).filter(models.Post.id == post_id).first()
if not post:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Post with ID {post_id} not found"
)
return post
# Create post
@router.post("/", response_model=schemas.PostResponse, status_code=status.HTTP_201_CREATED)
async def create_post(
post: schemas.PostCreate,
db: Session = Depends(get_db)
):
"""
Create a new blog post
"""
new_post = models.Post(**post.dict())
db.add(new_post)
db.commit()
db.refresh(new_post)
return new_post
# Update post
@router.put("/{post_id}", response_model=schemas.PostResponse)
async def update_post(
post_id: int,
post_update: schemas.PostUpdate,
db: Session = Depends(get_db)
):
"""
Update an existing blog post
"""
post_query = db.query(models.Post).filter(models.Post.id == post_id)
post = post_query.first()
if not post:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Post with ID {post_id} not found"
)
# Update only provided fields
update_data = post_update.dict(exclude_unset=True)
post_query.update(update_data, synchronize_session=False)
db.commit()
db.refresh(post)
return post
# Delete post
@router.delete("/{post_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_post(post_id: int, db: Session = Depends(get_db)):
"""
Delete a blog post
"""
post_query = db.query(models.Post).filter(models.Post.id == post_id)
post = post_query.first()
if not post:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Post with ID {post_id} not found"
)
post_query.delete(synchronize_session=False)
db.commit()
return None
# Search posts
@router.get("/search/", response_model=List[schemas.PostResponse])
async def search_posts(
q: str,
db: Session = Depends(get_db)
):
"""
Search blog posts by title or content
"""
posts = db.query(models.Post).filter(
(models.Post.title.contains(q)) |
(models.Post.content.contains(q))
).all()
return posts
Tallaabada 5: Codsiga Ugu Weyn
Abuur app/main.py:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.database import engine
from app import models
from app.routers import posts
# Create database tables
models.Base.metadata.create_all(bind=engine)
# Initialize FastAPI
app = FastAPI(
title="Blog API",
description="A modern blog API built with FastAPI",
version="1.0.0",
docs_url="/docs", # Swagger UI
redoc_url="/redoc" # ReDoc
)
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production, specify actual origins
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(posts.router)
# Root endpoint
@app.get("/")
async def root():
return {
"message": "Welcome to Blog API",
"docs": "/docs",
"version": "1.0.0"
}
# Health check
@app.get("/health")
async def health_check():
return {"status": "healthy"}
🚀 Socodsiinta Codsiga
Bilow server-ka FastAPI:
uvicorn app.main:app --reload
API-gaaga hadda waa diyaar:
- API: http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
🧪 Tijaabinta API-ga
Isticmaalka curl
Abuur qoraal:
curl -X POST "http://localhost:8000/api/posts/" \
-H "Content-Type: application/json" \
-d '{
"title": "Getting Started with FastAPI",
"content": "FastAPI is an amazing framework for building APIs quickly!",
"author": "Shutiye Dev",
"published": 1
}'
Hel dhammaan qoraallada:
curl "http://localhost:8000/api/posts/"
Hel qoraal gaar ah:
curl "http://localhost:8000/api/posts/1"
Cusboonaysii qoraal:
curl -X PUT "http://localhost:8000/api/posts/1" \
-H "Content-Type: application/json" \
-d '{
"title": "FastAPI Advanced Guide",
"content": "Updated content about FastAPI features"
}'
Raadi qoraallo:
curl "http://localhost:8000/api/posts/search/?q=FastAPI"
Isticmaalka Python Requests
import requests
# Create a post
response = requests.post(
"http://localhost:8000/api/posts/",
json={
"title": "Python FastAPI Tutorial",
"content": "Learn FastAPI step by step",
"author": "Dev Team"
}
)
print(response.json())
# Get all posts
response = requests.get("http://localhost:8000/api/posts/")
print(response.json())
✨ Astaamo Hormarsan
1. Hawlgallo Kayd Async ah
Si aad u hesho waxqabad fiican, isticmaal hawlgallo async:
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite+aiosqlite:///./blog.db"
engine = create_async_engine(DATABASE_URL)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_async_db():
async with AsyncSessionLocal() as session:
yield session
2. Aqoonsiga leh JWT
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@router.get("/protected")
async def protected_route(token: str = Depends(oauth2_scheme)):
# Verify token
return {"message": "This is protected!"}
3. Soo-galinta Faylka
from fastapi import File, UploadFile
@router.post("/upload")
async def upload_file(file: UploadFile = File(...)):
contents = await file.read()
# Process file
return {"filename": file.filename, "size": len(contents)}
4. Hawlo Asal-xisaabeed (Background Tasks)
from fastapi import BackgroundTasks
def send_email(email: str, message: str):
# Send email logic
print(f"Sending email to {email}: {message}")
@router.post("/send-notification")
async def send_notification(
email: str,
background_tasks: BackgroundTasks
):
background_tasks.add_task(send_email, email, "Post created!")
return {"message": "Notification will be sent"}
🎯 Habraacyada Ugu Fiican
1. Adeegsiga Dependency Injection
from fastapi import Depends
def common_parameters(skip: int = 0, limit: int = 100):
return {"skip": skip, "limit": limit}
@router.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
2. Maareynta Khaladaadka si Habboon
from fastapi import HTTPException
@router.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id not in items:
raise HTTPException(
status_code=404,
detail="Item not found",
headers={"X-Error": "Custom header"}
)
return items[item_id]
3. Isticmaalka Environment Variables
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
secret_key: str
class Config:
env_file = ".env"
settings = Settings()
4. Ku dar Model-yada Jawaabta
@router.get("/users/", response_model=List[UserResponse])
async def get_users():
return users # Si toos ah ayay u hubisaa uguna diyaargarowdaa
📊 Talooyin Waxqabad
- Isticmaal async/await hawlaha I/O
- Ku dar caching Redis
- Ku dar connection pooling database-ka
- Ku dar pagination xogta ballaaran
- Hagaaji queries-ka adigoo isticmaalaya indexes
- Cadaadi jawaabaha (gzip)
🚀 Daabacaadda
Adeegsiga Docker
Abuur Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY ./app ./app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Dhiso oo socodsi:
docker build -t fastapi-blog .
docker run -p 8000:8000 fastapi-blog
Adeegsiga Uvicorn ee Production
uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4
🎓 Qodobbo Muhiim ah
- FastAPI waa degdeg: Waxqabad la mid ah Node.js iyo Go
- Type hints: Xaqiijin iyo dukumenti toos ah
- Python casri ah: Async/await diyaar u ah
- Khibrad horumarineed oo fiican: Auto-completion iyo DX heer sare ah
- Production-ready: Taageero amni iyo waxqabad oo dhisan
📚 Maxaa Xiga?
- Ku dar aqoonsiga OAuth2 iyo JWT
- Hirgeli WebSocket astaamo waqtiga-dhabta ah
- Ku dar taageerada GraphQL
- La shaqee Celery hawlaha background-ka
- Deji la socodka Prometheus
- Ku daabac AWS, Azure, ama Google Cloud
FastAPI waa doorashada ugu habboon ee dhisidda API-yo casri ah oo waxqabadkoodu sarreeyo. Sahlan, degdeg, oo awood badan – bilow mashruucaaga maanta!
Wax badan ka baro FastAPI adigoo eegaya dukumentiga rasmiga ah ama sahaminta casharradeenna Python.
