Spaces:
Running
Running
Update image_api.py
Browse files- image_api.py +18 -2
image_api.py
CHANGED
@@ -1,19 +1,35 @@
|
|
1 |
-
from fastapi import APIRouter, HTTPException, Query
|
|
|
2 |
import requests
|
3 |
import os
|
4 |
from typing import List, Optional
|
5 |
from pydantic import BaseModel
|
|
|
6 |
|
7 |
router = APIRouter()
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
class UnsplashResponse(BaseModel):
|
10 |
images: List[str]
|
11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
@router.get("/unsplash-images/", response_model=UnsplashResponse)
|
13 |
async def get_unsplash_images(
|
14 |
query: str,
|
15 |
images_per_page: Optional[int] = Query(4, alias="per_page", ge=1, le=30),
|
16 |
-
page: Optional[int] = Query(1, ge=1)
|
|
|
17 |
):
|
18 |
url = "https://api.unsplash.com/search/photos"
|
19 |
params = {
|
|
|
1 |
+
from fastapi import APIRouter, HTTPException, Query, Security, Depends
|
2 |
+
from fastapi.security import APIKeyHeader
|
3 |
import requests
|
4 |
import os
|
5 |
from typing import List, Optional
|
6 |
from pydantic import BaseModel
|
7 |
+
import logging
|
8 |
|
9 |
router = APIRouter()
|
10 |
|
11 |
+
# Setup logging
|
12 |
+
logger = logging.getLogger(__name__)
|
13 |
+
|
14 |
+
# Setup API key authentication
|
15 |
+
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
|
16 |
+
CHAT_AUTH_KEY = os.environ.get("CHAT_AUTH_KEY")
|
17 |
+
|
18 |
class UnsplashResponse(BaseModel):
|
19 |
images: List[str]
|
20 |
|
21 |
+
async def verify_api_key(api_key: str = Security(api_key_header)):
|
22 |
+
if api_key != CHAT_AUTH_KEY:
|
23 |
+
logger.warning("Invalid API key used")
|
24 |
+
raise HTTPException(status_code=403, detail="Could not validate credentials")
|
25 |
+
return api_key
|
26 |
+
|
27 |
@router.get("/unsplash-images/", response_model=UnsplashResponse)
|
28 |
async def get_unsplash_images(
|
29 |
query: str,
|
30 |
images_per_page: Optional[int] = Query(4, alias="per_page", ge=1, le=30),
|
31 |
+
page: Optional[int] = Query(1, ge=1),
|
32 |
+
api_key: str = Depends(verify_api_key)
|
33 |
):
|
34 |
url = "https://api.unsplash.com/search/photos"
|
35 |
params = {
|