zd / app /api /v1 /endpoints /dictionary.py
Juna190825's picture
Create app/api/v1/endpoints/dictionary.py
83348ff verified
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.db.session import SessionLocal
from app.schemas.dictionary_entry import DictionaryEntry, DictionaryEntryCreate
from app.services.dictionary_service import search_entries, get_entry, create_entry
router = APIRouter()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@router.get("/entries", response_model=List[DictionaryEntry])
def search(query: str = "", db: Session = Depends(get_db)):
return search_entries(db, query)
@router.get("/entries/{entry_id}", response_model=DictionaryEntry)
def read_entry(entry_id: int, db: Session = Depends(get_db)):
entry = get_entry(db, entry_id)
if not entry:
raise HTTPException(status_code=404, detail="Entry not found")
return entry
@router.post("/entries", response_model=DictionaryEntry, status_code=201)
def create(data: DictionaryEntryCreate, db: Session = Depends(get_db)):
return create_entry(db, data)