From 468390231ba4064e7460412456fbac2bc6d7727e Mon Sep 17 00:00:00 2001 From: Joseph Ferano Date: Wed, 17 May 2023 20:29:50 +0700 Subject: [PATCH] Replace manual response with HTTPException for errors, validate URLs --- api.py | 25 ++++++++++++++----------- requirements.txt | 1 + 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/api.py b/api.py index 2e06683..99d82f2 100644 --- a/api.py +++ b/api.py @@ -1,8 +1,9 @@ -from fastapi import FastAPI, Response +from fastapi import FastAPI, HTTPException from fastapi.responses import RedirectResponse, FileResponse from fastapi.staticfiles import StaticFiles import couchdb import uuid +import validators app = FastAPI() app.mount("/static", StaticFiles(directory="static", html=True), name="static") @@ -26,29 +27,31 @@ async def read_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): +async def read_url(url_id): db = couch["urls"] if url_id in db: return db[url_id] else: - response.status_code = 404 - return { "error": "Url not found" } + raise HTTPException(status_code=404, detail="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 + if validators.url(body["url"]): + db = couch["urls"] + # TODO: Calculate how many unique IDs we are actually generating + url_id = uuid.uuid4().hex[:6] + db[url_id] = { "full_url": body["url"], "user_id": body["username"] } + return { "shortenedUrl": "http://localhost:8000/" + url_id } + else: + raise HTTPException(status_code=400, detail="Url provided is invalid") @app.delete("/api/v1/urls/{url_id}") -async def delete_url(url_id, response: Response): +async def delete_url(url_id): 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" } + raise HTTPException(status_code=404, detail="Url not found") diff --git a/requirements.txt b/requirements.txt index 5758adb..c511b6c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ fastapi uvicorn couchdb aiofiles +validators