Spaces:
Running
Running
File size: 1,079 Bytes
2525835 |
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 |
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]
@router.get("/unsplash-images/", response_model=UnsplashResponse)
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) |