49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
from fastapi import FastAPI, Response
|
|
from fastapi.responses import RedirectResponse
|
|
import couchdb
|
|
import uuid
|
|
|
|
app = FastAPI()
|
|
|
|
couch = couchdb.Server("http://admin:password@127.0.0.1:5984")
|
|
|
|
@app.get("/{url_id}", status_code=301)
|
|
async def redirect_urls(url_id):
|
|
target_url = couch["urls"][url_id].get('full_url')
|
|
return RedirectResponse(target_url)
|
|
|
|
# TODO: Get JWT tokens working and use that to return only the user's urls
|
|
# TODO: Look into how FastAPI handles the Authentication header
|
|
@app.get("/api/v1/urls")
|
|
async def read_urls():
|
|
db = couch["urls"]
|
|
return [ { id: db[id].get('full_url') } for id in db ]
|
|
|
|
@app.get("/api/v1/urls/{url_id}")
|
|
async def read_url(url_id, response: Response):
|
|
db = couch["urls"]
|
|
if url_id in db:
|
|
return db[url_id]
|
|
else:
|
|
response.status_code = 404
|
|
return { "error": "Url not found" }
|
|
|
|
# TODO: Throttle
|
|
# TODO: If user not found, generate a new JWT
|
|
@app.put("/api/v1/urls")
|
|
async def create_url(body: dict):
|
|
db = couch["urls"]
|
|
url_id = uuid.uuid4().hex[:6]
|
|
db[url_id] = { "full_url": body["url"], "user_id": body["username"] }
|
|
return
|
|
|
|
@app.delete("/api/v1/urls/{url_id}")
|
|
async def delete_url(url_id, response: Response):
|
|
db = couch["urls"]
|
|
if url_id in db:
|
|
del db[url_id]
|
|
return { "message": "Url deleted" }
|
|
else:
|
|
response.status_code = 404
|
|
return { "error": "Url not found" }
|