-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
405 lines (359 loc) · 13.5 KB
/
main.py
File metadata and controls
405 lines (359 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
"""
OPTCG API — FastAPI backend
Validated against:
- Render deployment docs (host 0.0.0.0, $PORT)
- Pokemon TCG API response conventions
- FastAPI + psycopg2 best practices
Endpoints:
GET / — API info
GET /sets — all sets
GET /sets/{id}/cards — cards in a set
GET /cards — all cards with filters + pagination
GET /cards/{id} — single card + all sets it appears in
Docs: /docs (Swagger UI auto-generated by FastAPI)
"""
import os
from typing import Optional
from contextlib import contextmanager
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
import psycopg2
import psycopg2.extras
from dotenv import load_dotenv
load_dotenv()
tags_metadata = [
{
"name": "Info",
"description": "API status and metadata.",
},
{
"name": "Sets",
"description": "Browse booster packs and starter decks. Each set has a unique ID like `OP-01` or `ST-01`.",
},
{
"name": "Cards",
"description": "Search, filter, and retrieve individual cards. Supports pagination and all major filter combinations.",
},
{
"name": "Images",
"description": "Proxy card artwork from the official One Piece Card Game site. Returns PNG with CORS headers.",
},
]
app = FastAPI(
title="OPTCG API",
description=(
"**Free REST API for One Piece TCG card data.**\n\n"
"Cards, sets, filters, and image proxying — built for "
"[OPBindr](https://opbindr.com) and the OPTCG community.\n\n"
"- Pagination follows the [Pokemon TCG API](https://pokemontcg.io/) convention (`page` / `pageSize`)\n"
"- All card IDs are uppercase (e.g. `OP01-001`, `ST01-001`)\n"
"- Image proxy adds CORS headers so you can use card art directly in the browser"
),
version="1.0.0",
openapi_tags=tags_metadata,
docs_url=None, # we serve custom /docs below
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["GET", "HEAD"],
allow_headers=["*"],
)
@app.get("/docs", include_in_schema=False)
async def scalar_docs():
return HTMLResponse("""
<!DOCTYPE html>
<html>
<head>
<title>OPTCG API — Docs</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<script id="api-reference" data-url="/openapi.json"></script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>
""")
# ── Database ──────────────────────────────────────────────────────────────────
# Connection-per-request is correct for Render free tier + Supabase session
# pooler. Render sleeps between requests so a persistent pool would be dropped
# anyway. Supabase's session pooler handles actual connection pooling server-side.
@contextmanager
def get_db():
"""Open a connection, yield cursor, always close on exit."""
conn = psycopg2.connect(
os.environ["DATABASE_URL"],
cursor_factory=psycopg2.extras.RealDictCursor,
)
try:
cur = conn.cursor()
yield cur
finally:
conn.close()
def fetch(sql: str, params=None) -> list:
with get_db() as cur:
cur.execute(sql, params or [])
return cur.fetchall()
def fetch_one(sql: str, params=None):
with get_db() as cur:
cur.execute(sql, params or [])
return cur.fetchone()
# ── Routes ────────────────────────────────────────────────────────────────────
@app.get(
"/",
tags=["Info"],
summary="API Info",
description="Returns API name, version, docs URL, and a list of available endpoints.",
responses={
200: {
"description": "API metadata",
"content": {
"application/json": {
"example": {
"name": "OPTCG API",
"version": "1.0.0",
"docs": "/docs",
"endpoints": [
"GET /sets",
"GET /sets/{id}/cards",
"GET /cards",
"GET /cards/{id}",
"GET /images/{card_id}",
],
}
}
},
}
},
)
def root():
return {
"name": "OPTCG API",
"version": "1.0.0",
"docs": "/docs",
"endpoints": [
"GET /sets",
"GET /sets/{id}/cards",
"GET /cards",
"GET /cards/{id}",
"GET /images/{card_id}",
],
}
@app.api_route(
"/sets",
methods=["GET", "HEAD"],
tags=["Sets"],
summary="List All Sets",
description="Returns every set (booster packs, starter decks, promo packs) ordered newest first.",
responses={
200: {
"description": "All sets",
"content": {
"application/json": {
"example": {
"count": 2,
"data": [
{"id": "OP01", "pack_id": "550101", "label": "Romance Dawn [OP-01]", "card_count": 121},
{"id": "ST01", "pack_id": "550001", "label": "Straw Hat Crew [ST-01]", "card_count": 17},
],
}
}
},
}
},
)
def get_sets():
rows = fetch("SELECT * FROM sets ORDER BY pack_id DESC")
return {"count": len(rows), "data": rows}
@app.get(
"/sets/{set_id}/cards",
tags=["Sets"],
summary="Get Cards in a Set",
description=(
"Returns all cards belonging to a specific set, ordered by card ID.\n\n"
"**Example:** `/sets/OP01/cards` returns all cards from the *Romance Dawn* booster."
),
)
def get_set_cards(set_id: str):
s = fetch_one("SELECT * FROM sets WHERE id = %s", [set_id.upper()])
if not s:
raise HTTPException(404, f"Set '{set_id}' not found")
cards = fetch("""
SELECT c.*
FROM cards c
JOIN card_sets cs ON cs.card_id = c.id
WHERE cs.set_id = %s
ORDER BY c.id
""", [set_id.upper()])
return {"set": s, "count": len(cards), "data": cards}
@app.get(
"/cards/{card_id}",
tags=["Cards"],
summary="Get a Single Card",
description=(
"Returns full card data plus every set the card appears in.\n\n"
"**Example:** `/cards/OP01-001` returns Roronoa Zoro with its set memberships."
),
responses={
200: {
"description": "Full card object with sets",
"content": {
"application/json": {
"example": {
"id": "OP01-001",
"base_id": "OP01-001",
"name": "Roronoa Zoro",
"category": "Character",
"colors": ["Green"],
"rarity": "Common",
"cost": 3,
"power": 5000,
"counter": 0,
"attributes": ["Slash"],
"types": ["Supernovas", "Straw Hat Crew"],
"effect": None,
"trigger": None,
"image_url": "https://en.onepiece-cardgame.com/images/cardlist/card/OP01-001.png",
"parallel": False,
"sets": [
{"id": "OP01", "pack_id": "550101", "label": "Romance Dawn [OP-01]", "card_count": 121}
],
}
}
},
},
404: {
"description": "Card not found",
"content": {
"application/json": {
"example": {"detail": "Card 'XX99-999' not found"}
}
},
},
},
)
def get_card(card_id: str):
card = fetch_one("SELECT * FROM cards WHERE id = %s", [card_id.upper()])
if not card:
raise HTTPException(404, f"Card '{card_id}' not found")
sets = fetch("""
SELECT s.*
FROM sets s
JOIN card_sets cs ON cs.set_id = s.id
WHERE cs.card_id = %s
ORDER BY s.pack_id
""", [card_id.upper()])
return {**card, "sets": sets}
@app.api_route(
"/cards",
methods=["GET", "HEAD"],
tags=["Cards"],
summary="Search Cards",
description=(
"Search and filter the full card database with pagination.\n\n"
"**Filters** — all optional and combinable:\n"
"- `set_id` — restrict to a single set (e.g. `OP01`)\n"
"- `color` — card color (`Red`, `Blue`, `Green`, `Purple`, `Black`, `Yellow`)\n"
"- `category` — card type (`Leader`, `Character`, `Event`, `Stage`, `Don`)\n"
"- `rarity` — `Leader`, `Common`, `Uncommon`, `Rare`, `SuperRare`, `SecretRare`\n"
"- `name` — partial text search (case insensitive)\n"
"- `parallel` — `true` for alt-art only, `false` for base only\n"
"- `variant_type` — parallel style: `alt_art`, `reprint`, `manga`, `serial`\n"
"- `min_power` / `max_power` — power range\n"
"- `min_cost` / `max_cost` — cost range\n\n"
"**Pagination** follows the Pokemon TCG API convention: `page` (default 1) and `page_size` (default 50, max 500)."
),
)
def get_cards(
# --- filters ---
set_id: Optional[str] = Query(None, description="Filter by set e.g. OP-01"),
color: Optional[str] = Query(None, description="Red, Blue, Green, Purple, Black, Yellow"),
category: Optional[str] = Query(None, description="Leader, Character, Event, Stage, Don"),
rarity: Optional[str] = Query(None, description="Leader, Common, Uncommon, Rare, SuperRare, SecretRare"),
name: Optional[str] = Query(None, description="Partial name search"),
parallel: Optional[bool] = Query(None, description="true=parallel only, false=base only"),
variant_type: Optional[str] = Query(None, description="alt_art, reprint, manga, serial"),
min_power: Optional[int] = Query(None, description="Min power"),
max_power: Optional[int] = Query(None, description="Max power"),
min_cost: Optional[int] = Query(None, description="Min cost"),
max_cost: Optional[int] = Query(None, description="Max cost"),
# --- pagination (matches Pokemon TCG API convention) ---
page: int = Query(1, ge=1, description="Page number"),
page_size: int = Query(50, ge=1, le=500, description="Results per page (max 500)"),
):
conditions, params = [], []
if set_id:
conditions.append(
"EXISTS (SELECT 1 FROM card_sets cs WHERE cs.card_id = c.id AND cs.set_id = %s)"
)
params.append(set_id.upper())
if color:
conditions.append("%s = ANY(c.colors)")
params.append(color.capitalize())
if category:
conditions.append("c.category ILIKE %s")
params.append(category)
if rarity:
conditions.append("c.rarity ILIKE %s")
params.append(rarity)
if name:
conditions.append("c.name ILIKE %s")
params.append(f"%{name}%")
if parallel is not None:
conditions.append("c.parallel = %s")
params.append(parallel)
if variant_type:
conditions.append("c.variant_type ILIKE %s")
params.append(variant_type)
if min_power is not None:
conditions.append("c.power >= %s")
params.append(min_power)
if max_power is not None:
conditions.append("c.power <= %s")
params.append(max_power)
if min_cost is not None:
conditions.append("c.cost >= %s")
params.append(min_cost)
if max_cost is not None:
conditions.append("c.cost <= %s")
params.append(max_cost)
where = ("WHERE " + " AND ".join(conditions)) if conditions else ""
offset = (page - 1) * page_size
total_row = fetch_one(f"SELECT COUNT(*) AS total FROM cards c {where}", params)
total = total_row["total"]
cards = fetch(f"""
SELECT c.*
FROM cards c
{where}
ORDER BY c.id
LIMIT %s OFFSET %s
""", params + [page_size, offset])
return {
"count": len(cards),
"totalCount": total,
"page": page,
"pageSize": page_size,
"data": cards,
}
@app.get(
"/images/{card_id}",
tags=["Images"],
summary="Proxy Card Image",
description=(
"Fetches the card image from the official One Piece Card Game site and serves it "
"with CORS headers and a 24-hour cache.\n\n"
"**Example:** `/images/OP01-001` returns the PNG artwork for that card.\n\n"
"Returns `404` if the card image does not exist upstream."
),
)
async def proxy_image(card_id: str):
import httpx
from fastapi.responses import Response
url = f"https://en.onepiece-cardgame.com/images/cardlist/card/{card_id}.png"
async with httpx.AsyncClient() as client:
r = await client.get(url, headers={"Referer": "https://en.onepiece-cardgame.com/"}, follow_redirects=True)
if r.status_code != 200:
return Response(status_code=404)
return Response(content=r.content, media_type="image/png", headers={"Cache-Control": "public, max-age=86400", "Access-Control-Allow-Origin": "*"})