Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

Add URL normalization to screenshot endpoint

Abi Raja7ca63f85326f
diff --git a/backend/routes/screenshot.py b/backend/routes/screenshot.py
index 258cd7e3..11479b7f 100644
--- a/backend/routes/screenshot.py
+++ b/backend/routes/screenshot.py
@@ -1,11 +1,33 @@
import base64
-from fastapi import APIRouter
+from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import httpx
+from urllib.parse import urlparse
router = APIRouter()
+def normalize_url(url: str) -> str:
+ """
+ Normalize URL to ensure it has a proper protocol.
+ If no protocol is specified, default to https://
+ """
+ url = url.strip()
+
+ # Parse the URL
+ parsed = urlparse(url)
+
+ # If no scheme (protocol) is provided, add https://
+ if not parsed.scheme:
+ # Handle cases like "example.com" or "www.example.com"
+ url = f"https://{url}"
+ elif parsed.scheme not in ['http', 'https']:
+ # Only allow http and https protocols
+ raise ValueError(f"Unsupported protocol: {parsed.scheme}")
+
+ return url
+
+
def bytes_to_data_url(image_bytes: bytes, mime_type: str) -> str:
base64_image = base64.b64encode(image_bytes).decode("utf-8")
return f"data:{mime_type};base64,{base64_image}"
@@ -57,10 +79,20 @@ async def app_screenshot(request: ScreenshotRequest):
url = request.url
api_key = request.apiKey
- # TODO: Add error handling
- image_bytes = await capture_screenshot(url, api_key=api_key)
-
- # Convert the image bytes to a data url
- data_url = bytes_to_data_url(image_bytes, "image/png")
-
- return ScreenshotResponse(url=data_url)
+ try:
+ # Normalize the URL
+ normalized_url = normalize_url(url)
+
+ # Capture screenshot with normalized URL
+ image_bytes = await capture_screenshot(normalized_url, api_key=api_key)
+
+ # Convert the image bytes to a data url
+ data_url = bytes_to_data_url(image_bytes, "image/png")
+
+ return ScreenshotResponse(url=data_url)
+ except ValueError as e:
+ # Handle URL normalization errors
+ raise HTTPException(status_code=500, detail=str(e))
+ except Exception as e:
+ # Handle other errors
+ raise HTTPException(status_code=500, detail=f"Error capturing screenshot: {str(e)}")
diff --git a/design-docs/todo-list.md b/design-docs/todo-list.md
new file mode 100644
index 00000000..7dc22ef4
--- /dev/null
+++ b/design-docs/todo-list.md
@@ -0,0 +1 @@
+- enter should trigger generation in URL textbox