summaryrefslogtreecommitdiff
path: root/routers/tmdb.py
blob: 5f7943f4b628f703ecfa60ea612552d0b2c73447 (plain)
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
import httpx
from dotenv import load_dotenv
from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse

from services.tmdb import TMDBNotConfiguredError, search_movies, movie_images

load_dotenv()

router = APIRouter(prefix="/tmdb", tags=["tmdb"])


@router.get("/search")
async def search_tmdb(q: str = Query(..., min_length=2)):
    try:
        return {"results": await search_movies(q, limit=8, include_details=True)}
    except TMDBNotConfiguredError:
        return JSONResponse(
            status_code=503,
            content={
                "error": "TMDB_API_KEY is not configured.",
                "results": [],
            },
        )
    except httpx.HTTPError:
        return JSONResponse(
            status_code=502,
            content={
                "error": "TMDB search failed. Check your API key and try again.",
                "results": [],
            },
        )


@router.get("/posters")
async def tmdb_posters(tmdb_id: int = Query(...)):
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            urls = await movie_images(client, tmdb_id)
        return {"posters": urls}
    except TMDBNotConfiguredError:
        return JSONResponse(
            status_code=503,
            content={"error": "TMDB_API_KEY is not configured.", "posters": []},
        )