Spaces:
Running
Running
from fastapi import APIRouter, HTTPException, Query | |
import requests | |
import os | |
from typing import List, Optional | |
from pydantic import BaseModel | |
router = APIRouter() | |
class UnsplashResponse(BaseModel): | |
images: List[str] | |
async def get_unsplash_images( | |
query: str, | |
images_per_page: Optional[int] = Query(4, alias="per_page", ge=1, le=30), | |
page: Optional[int] = Query(1, ge=1) | |
): | |
url = "https://api.unsplash.com/search/photos" | |
params = { | |
"query": query, | |
"client_id": os.environ.get("UNSPLASH_API_KEY"), | |
"per_page": images_per_page, | |
"page": page | |
} | |
response = requests.get(url, params=params) | |
if response.status_code != 200: | |
raise HTTPException(status_code=response.status_code, detail="Failed to fetch images from Unsplash") | |
data = response.json() | |
images = [] | |
if 'results' in data: | |
for photo in data['results']: | |
images.append(photo['urls']['regular']) | |
return UnsplashResponse(images=images) |