web-crawling / image_api.py
pvanand's picture
Update image_api.py
ba1a9b3 verified
Raw History Blame Contribute Delete
1.65 kB
from fastapi import APIRouter, HTTPException, Query, Security, Depends
from fastapi.security import APIKeyHeader
import requests
import os
from typing import List, Optional
from pydantic import BaseModel
import logging
router = APIRouter()
# Setup logging
logger = logging.getLogger(__name__)
# Setup API key authentication
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
CHAT_AUTH_KEY = os.environ.get("CHAT_AUTH_KEY")
class UnsplashResponse(BaseModel):
images: List[str]
async def verify_api_key(api_key: str = Security(api_key_header)):
if api_key != CHAT_AUTH_KEY:
logger.warning("Invalid API key used")
raise HTTPException(status_code=403, detail="Could not validate credentials")
return api_key
@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),
api_key: str = Depends(verify_api_key)
):
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)