generated from admin/template
podex-api completed with swagger & docker compose
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
DATABASE_URL = "sqlite:///./pokedex.db"
|
||||
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
connect_args={"check_same_thread": False},
|
||||
)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,103 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, List, Optional
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
|
||||
def _timestamp() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
|
||||
|
||||
|
||||
def error_body(
|
||||
status_code: int,
|
||||
error_code: str,
|
||||
message: str,
|
||||
path: str,
|
||||
errors: Optional[List[Any]] = None,
|
||||
) -> dict:
|
||||
return {
|
||||
"statusCode": status_code,
|
||||
"errorCode": error_code,
|
||||
"message": message,
|
||||
"errors": errors,
|
||||
"timestamp": _timestamp(),
|
||||
"path": path,
|
||||
}
|
||||
|
||||
|
||||
class AppError(Exception):
|
||||
def __init__(
|
||||
self,
|
||||
status_code: int,
|
||||
error_code: str,
|
||||
message: str,
|
||||
errors: Optional[List[Any]] = None,
|
||||
):
|
||||
self.status_code = status_code
|
||||
self.error_code = error_code
|
||||
self.message = message
|
||||
self.errors = errors
|
||||
|
||||
|
||||
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=error_body(
|
||||
exc.status_code, exc.error_code, exc.message, request.url.path, exc.errors
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def http_exception_handler(
|
||||
request: Request, exc: StarletteHTTPException
|
||||
) -> JSONResponse:
|
||||
code = "INTERNAL_SERVER_ERROR"
|
||||
if exc.status_code == 404:
|
||||
code = "POKEMON_NOT_FOUND"
|
||||
elif exc.status_code == 400:
|
||||
code = "VALIDATION_FAILED"
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=error_body(exc.status_code, code, str(exc.detail), request.url.path),
|
||||
)
|
||||
|
||||
|
||||
async def validation_exception_handler(
|
||||
request: Request, exc: RequestValidationError
|
||||
) -> JSONResponse:
|
||||
errors = []
|
||||
for err in exc.errors():
|
||||
loc = err.get("loc", [])
|
||||
field = ".".join(str(x) for x in loc if x not in ("query", "path", "body"))
|
||||
errors.append(
|
||||
{
|
||||
"field": field,
|
||||
"message": err.get("msg", "invalid value"),
|
||||
"value": err.get("input"),
|
||||
}
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=400,
|
||||
content=error_body(
|
||||
400,
|
||||
"VALIDATION_FAILED",
|
||||
"Validation failed for query parameters",
|
||||
request.url.path,
|
||||
errors,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content=error_body(
|
||||
500,
|
||||
"INTERNAL_SERVER_ERROR",
|
||||
"An unexpected error occurred on the server",
|
||||
request.url.path,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,130 @@
|
||||
import csv
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import models
|
||||
|
||||
DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")
|
||||
|
||||
|
||||
def _read(name: str):
|
||||
path = os.path.join(DATA_DIR, name)
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
with open(path, "r", encoding="utf-8-sig", newline="") as f:
|
||||
return list(csv.DictReader(f))
|
||||
|
||||
|
||||
def _int(value):
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return int(float(value))
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def _dec(value):
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return Decimal(str(value))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def load_all(db: Session) -> None:
|
||||
if db.query(models.Pokemon).first() is not None:
|
||||
return
|
||||
|
||||
for row in _read("types.csv"):
|
||||
db.add(
|
||||
models.Type(
|
||||
id=_int(row.get("id")),
|
||||
name=row.get("name") or row.get("identifier") or "",
|
||||
color_hex=row.get("color_hex") or row.get("color"),
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
for row in _read("pokemons.csv"):
|
||||
db.add(
|
||||
models.Pokemon(
|
||||
id=_int(row.get("id")),
|
||||
name=row.get("name") or row.get("identifier") or "",
|
||||
height_m=_dec(row.get("height_m") or row.get("height")),
|
||||
weight_kg=_dec(row.get("weight_kg") or row.get("weight")),
|
||||
image_url=row.get("image_url"),
|
||||
description=row.get("description"),
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
for row in _read("pokemon_types.csv"):
|
||||
db.add(
|
||||
models.PokemonType(
|
||||
pokemon_id=_int(row.get("pokemon_id")),
|
||||
type_id=_int(row.get("type_id")),
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
for row in _read("pokemon_stats.csv"):
|
||||
db.add(
|
||||
models.PokemonStat(
|
||||
pokemon_id=_int(row.get("pokemon_id")),
|
||||
hp=_int(row.get("hp")),
|
||||
atk=_int(row.get("atk")),
|
||||
def_=_int(row.get("def")),
|
||||
satk=_int(row.get("satk")),
|
||||
sdef=_int(row.get("sdef")),
|
||||
spd=_int(row.get("spd")),
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
for row in _read("move_categories.csv"):
|
||||
db.add(
|
||||
models.MoveCategory(
|
||||
id=_int(row.get("id")),
|
||||
name=row.get("name") or row.get("identifier") or "",
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
for row in _read("moves.csv"):
|
||||
db.add(
|
||||
models.Move(
|
||||
id=_int(row.get("id")),
|
||||
name=row.get("name") or row.get("identifier") or "",
|
||||
type_id=_int(row.get("type_id")),
|
||||
category_id=_int(row.get("category_id")),
|
||||
power=_int(row.get("power")),
|
||||
accuracy=_int(row.get("accuracy")),
|
||||
description=row.get("description"),
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
for row in _read("learn_methods.csv"):
|
||||
db.add(
|
||||
models.LearnMethod(
|
||||
id=_int(row.get("id")),
|
||||
name=row.get("name") or row.get("identifier") or "",
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
for row in _read("pokemon_moves.csv"):
|
||||
db.add(
|
||||
models.PokemonMove(
|
||||
id=_int(row.get("id")),
|
||||
pokemon_id=_int(row.get("pokemon_id")),
|
||||
move_id=_int(row.get("move_id")),
|
||||
level_learned=_int(row.get("level_learned")),
|
||||
learn_method_id=_int(row.get("learn_method_id")),
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
@@ -0,0 +1,35 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from . import models
|
||||
from .database import Base, engine, SessionLocal
|
||||
from .errors import (
|
||||
AppError,
|
||||
app_error_handler,
|
||||
http_exception_handler,
|
||||
unhandled_exception_handler,
|
||||
validation_exception_handler,
|
||||
)
|
||||
from .loader import load_all
|
||||
from .routers import pokemons
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
with SessionLocal() as _db:
|
||||
load_all(_db)
|
||||
|
||||
app = FastAPI(
|
||||
title="Pokédex API",
|
||||
version="1.0.0",
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
app.add_exception_handler(AppError, app_error_handler)
|
||||
app.add_exception_handler(StarletteHTTPException, http_exception_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_exception_handler)
|
||||
app.add_exception_handler(Exception, unhandled_exception_handler)
|
||||
|
||||
app.include_router(pokemons.router)
|
||||
@@ -0,0 +1,86 @@
|
||||
from sqlalchemy import Column, Integer, String, Numeric, Text, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from .database import Base
|
||||
|
||||
|
||||
class Pokemon(Base):
|
||||
__tablename__ = "pokemons"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False, index=True)
|
||||
height_m = Column(Numeric, nullable=True)
|
||||
weight_kg = Column(Numeric, nullable=True)
|
||||
image_url = Column(Text, nullable=True)
|
||||
description = Column(Text, nullable=True)
|
||||
|
||||
stats = relationship("PokemonStat", back_populates="pokemon", uselist=False)
|
||||
types = relationship("PokemonType", back_populates="pokemon")
|
||||
|
||||
|
||||
class Type(Base):
|
||||
__tablename__ = "types"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
color_hex = Column(String, nullable=True)
|
||||
|
||||
|
||||
class PokemonType(Base):
|
||||
__tablename__ = "pokemon_types"
|
||||
|
||||
pokemon_id = Column(Integer, ForeignKey("pokemons.id"), primary_key=True)
|
||||
type_id = Column(Integer, ForeignKey("types.id"), primary_key=True)
|
||||
|
||||
pokemon = relationship("Pokemon", back_populates="types")
|
||||
type = relationship("Type")
|
||||
|
||||
|
||||
class PokemonStat(Base):
|
||||
__tablename__ = "pokemon_stats"
|
||||
|
||||
pokemon_id = Column(Integer, ForeignKey("pokemons.id"), primary_key=True)
|
||||
hp = Column(Integer, nullable=True)
|
||||
atk = Column(Integer, nullable=True)
|
||||
def_ = Column("def", Integer, nullable=True)
|
||||
satk = Column(Integer, nullable=True)
|
||||
sdef = Column(Integer, nullable=True)
|
||||
spd = Column(Integer, nullable=True)
|
||||
|
||||
pokemon = relationship("Pokemon", back_populates="stats")
|
||||
|
||||
|
||||
class MoveCategory(Base):
|
||||
__tablename__ = "move_categories"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
|
||||
|
||||
class Move(Base):
|
||||
__tablename__ = "moves"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
type_id = Column(Integer, ForeignKey("types.id"), nullable=True)
|
||||
category_id = Column(Integer, ForeignKey("move_categories.id"), nullable=True)
|
||||
power = Column(Integer, nullable=True)
|
||||
accuracy = Column(Integer, nullable=True)
|
||||
description = Column(Text, nullable=True)
|
||||
|
||||
|
||||
class LearnMethod(Base):
|
||||
__tablename__ = "learn_methods"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
|
||||
|
||||
class PokemonMove(Base):
|
||||
__tablename__ = "pokemon_moves"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
pokemon_id = Column(Integer, ForeignKey("pokemons.id"), nullable=False)
|
||||
move_id = Column(Integer, ForeignKey("moves.id"), nullable=False)
|
||||
level_learned = Column(Integer, nullable=True)
|
||||
learn_method_id = Column(Integer, ForeignKey("learn_methods.id"), nullable=True)
|
||||
@@ -0,0 +1,187 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import or_, cast, String
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import models, schemas
|
||||
from ..database import get_db
|
||||
from ..errors import AppError
|
||||
|
||||
router = APIRouter(prefix="/api/v1/pokemons", tags=["pokemons"])
|
||||
|
||||
|
||||
@router.get("", response_model=schemas.PokemonListResponse)
|
||||
def list_pokemons(
|
||||
search: Optional[str] = Query(default=None),
|
||||
sort_by: str = Query(default="id"),
|
||||
order: str = Query(default="asc"),
|
||||
limit: int = Query(default=20),
|
||||
offset: int = Query(default=0),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
errors = []
|
||||
if sort_by not in ("id", "name"):
|
||||
errors.append(
|
||||
{
|
||||
"field": "sort_by",
|
||||
"message": "sort_by must be one of: 'id', 'name'",
|
||||
"value": sort_by,
|
||||
}
|
||||
)
|
||||
if order not in ("asc", "desc"):
|
||||
errors.append(
|
||||
{
|
||||
"field": "order",
|
||||
"message": "order must be one of: 'asc', 'desc'",
|
||||
"value": order,
|
||||
}
|
||||
)
|
||||
if limit < 1 or limit > 100:
|
||||
errors.append(
|
||||
{
|
||||
"field": "limit",
|
||||
"message": "limit must not be greater than 100",
|
||||
"value": limit,
|
||||
}
|
||||
)
|
||||
if offset < 0:
|
||||
errors.append(
|
||||
{
|
||||
"field": "offset",
|
||||
"message": "offset must be greater than or equal to 0",
|
||||
"value": offset,
|
||||
}
|
||||
)
|
||||
if errors:
|
||||
raise AppError(
|
||||
400, "VALIDATION_FAILED", "Validation failed for query parameters", errors
|
||||
)
|
||||
|
||||
query = db.query(models.Pokemon)
|
||||
|
||||
if search:
|
||||
term = f"%{search.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
models.Pokemon.name.ilike(term),
|
||||
cast(models.Pokemon.id, String).ilike(term),
|
||||
)
|
||||
)
|
||||
|
||||
column = models.Pokemon.id if sort_by == "id" else models.Pokemon.name
|
||||
query = query.order_by(column.desc() if order == "desc" else column.asc())
|
||||
|
||||
total = query.count()
|
||||
rows = query.offset(offset).limit(limit).all()
|
||||
|
||||
return schemas.PokemonListResponse(
|
||||
total=total,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
data=[
|
||||
schemas.PokemonListItem(
|
||||
id=r.id, name=r.name, image_url=r.image_url
|
||||
)
|
||||
for r in rows
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{id_or_name}", response_model=schemas.PokemonDetailResponse)
|
||||
def get_pokemon(id_or_name: str, db: Session = Depends(get_db)):
|
||||
pokemon = None
|
||||
|
||||
if id_or_name.isdigit():
|
||||
pokemon = db.query(models.Pokemon).filter(models.Pokemon.id == int(id_or_name)).first()
|
||||
|
||||
if pokemon is None:
|
||||
pokemon = (
|
||||
db.query(models.Pokemon)
|
||||
.filter(models.Pokemon.name.ilike(id_or_name))
|
||||
.first()
|
||||
)
|
||||
|
||||
if pokemon is None:
|
||||
raise AppError(
|
||||
404,
|
||||
"POKEMON_NOT_FOUND",
|
||||
f"Pokemon with identifier '{id_or_name}' was not found",
|
||||
)
|
||||
|
||||
type_rows = (
|
||||
db.query(models.Type)
|
||||
.join(models.PokemonType, models.PokemonType.type_id == models.Type.id)
|
||||
.filter(models.PokemonType.pokemon_id == pokemon.id)
|
||||
.all()
|
||||
)
|
||||
|
||||
types = [
|
||||
schemas.TypeItem(
|
||||
id=t.id,
|
||||
code=(t.name or "").upper() if t.name else None,
|
||||
name=t.name,
|
||||
color_hex=t.color_hex,
|
||||
)
|
||||
for t in type_rows
|
||||
]
|
||||
|
||||
color_hex = type_rows[0].color_hex if type_rows else None
|
||||
|
||||
stats_row = (
|
||||
db.query(models.PokemonStat)
|
||||
.filter(models.PokemonStat.pokemon_id == pokemon.id)
|
||||
.first()
|
||||
)
|
||||
|
||||
stats = schemas.StatsBlock(
|
||||
hp=stats_row.hp if stats_row else None,
|
||||
atk=stats_row.atk if stats_row else None,
|
||||
def_=stats_row.def_ if stats_row else None,
|
||||
satk=stats_row.satk if stats_row else None,
|
||||
sdef=stats_row.sdef if stats_row else None,
|
||||
spd=stats_row.spd if stats_row else None,
|
||||
)
|
||||
|
||||
move_names = [
|
||||
m.name
|
||||
for m in (
|
||||
db.query(models.Move)
|
||||
.join(models.PokemonMove, models.PokemonMove.move_id == models.Move.id)
|
||||
.filter(models.PokemonMove.pokemon_id == pokemon.id)
|
||||
.all()
|
||||
)
|
||||
]
|
||||
|
||||
about = schemas.AboutBlock(
|
||||
weight_kg=float(pokemon.weight_kg) if pokemon.weight_kg is not None else None,
|
||||
height_m=float(pokemon.height_m) if pokemon.height_m is not None else None,
|
||||
moves=move_names,
|
||||
description=pokemon.description,
|
||||
)
|
||||
|
||||
prev_id = (
|
||||
db.query(models.Pokemon.id)
|
||||
.filter(models.Pokemon.id < pokemon.id)
|
||||
.order_by(models.Pokemon.id.desc())
|
||||
.limit(1)
|
||||
.scalar()
|
||||
)
|
||||
next_id = (
|
||||
db.query(models.Pokemon.id)
|
||||
.filter(models.Pokemon.id > pokemon.id)
|
||||
.order_by(models.Pokemon.id.asc())
|
||||
.limit(1)
|
||||
.scalar()
|
||||
)
|
||||
|
||||
return schemas.PokemonDetailResponse(
|
||||
id=pokemon.id,
|
||||
name=pokemon.name,
|
||||
image_url=pokemon.image_url,
|
||||
color_hex=color_hex,
|
||||
types=types,
|
||||
about=about,
|
||||
stats=stats,
|
||||
navigation=schemas.NavigationBlock(prev_id=prev_id, next_id=next_id),
|
||||
)
|
||||
@@ -0,0 +1,60 @@
|
||||
from typing import List, Optional, Union
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class PokemonListItem(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
image_url: Optional[str] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class PokemonListResponse(BaseModel):
|
||||
total: int
|
||||
limit: int
|
||||
offset: int
|
||||
data: List[PokemonListItem]
|
||||
|
||||
|
||||
class TypeItem(BaseModel):
|
||||
id: int
|
||||
code: Optional[str] = None
|
||||
name: str
|
||||
color_hex: Optional[str] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class AboutBlock(BaseModel):
|
||||
weight_kg: Optional[float] = None
|
||||
height_m: Optional[float] = None
|
||||
moves: List[str] = []
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
class StatsBlock(BaseModel):
|
||||
hp: Optional[int] = None
|
||||
atk: Optional[int] = None
|
||||
def_: Optional[int] = None
|
||||
satk: Optional[int] = None
|
||||
sdef: Optional[int] = None
|
||||
spd: Optional[int] = None
|
||||
|
||||
|
||||
class NavigationBlock(BaseModel):
|
||||
prev_id: Optional[int] = None
|
||||
next_id: Optional[int] = None
|
||||
|
||||
|
||||
class PokemonDetailResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
image_url: Optional[str] = None
|
||||
color_hex: Optional[str] = None
|
||||
types: List[TypeItem] = []
|
||||
about: AboutBlock
|
||||
stats: StatsBlock
|
||||
navigation: NavigationBlock
|
||||
Reference in New Issue
Block a user