add GET method for shortening

This commit is contained in:
2026-03-19 21:48:14 +08:00
parent f7e3124797
commit a250ce4c1d
2 changed files with 11 additions and 6 deletions
+7 -4
View File
@@ -124,8 +124,8 @@ Health check endpoint.
---
### `POST /api/shorten`
Create a new short URL. No API key required.
### `POST / GET /api/shorten`
Create a new short URL (supports both `POST` and `GET`). No API key required.
Fields can be passed as **query parameters** (URL-encoded) or in a **JSON request body**.
Query parameters take precedence over body fields.
@@ -217,14 +217,17 @@ Increments `visit_count` on each hit.
## Example with `curl`
```bash
# Shorten a URL (JSON body)
# Shorten a URL (POST with JSON body)
curl -X POST http://localhost:8080/s/api/shorten \
-H "Content-Type: application/json" \
-d '{"url": "https://github.com"}'
# Shorten a URL (query parameters)
# Shorten a URL (POST with query parameters)
curl -X POST "http://localhost:8080/s/api/shorten?url=https%3A%2F%2Fgithub.com&retention_days=30"
# Shorten a URL (GET with query parameters)
curl "http://localhost:8080/s/api/shorten?url=https%3A%2F%2Fgithub.com"
# Follow the redirect
curl -L http://localhost:8080/s/aB3xYz
+4 -2
View File
@@ -6,7 +6,7 @@ Usage: python urlshort.py <config.json>
API (all routes are prefixed with base_path, e.g. /s):
GET / Frontend (or health check if no static/)
GET /api/health Health check
POST /api/shorten Create a short URL (no API key required)
POST/GET /api/shorten Create a short URL (no API key required)
GET /api/urls List all short URLs (API key required)
GET /api/urls/<code> Get info for a code (no API key required)
GET /api/lookup?url=<url> Look up by original URL (no API key required)
@@ -357,6 +357,9 @@ class Handler(BaseHTTPRequestHandler):
elif path == "/api/health":
self._send_json(200, {"status": "ok", "service": "url-shortener"})
elif path == "/api/shorten":
self._handle_shorten()
elif path == "/api/urls":
self._handle_list_urls()
@@ -433,7 +436,6 @@ class Handler(BaseHTTPRequestHandler):
self._error(400, "Invalid JSON body")
return
# url: query param takes precedence, then body
original_url = qs.get("url", [""])[0] or str(body.get("url", "")).strip()
if not original_url: