From 28314e386582d41560517d55183b059f44020076 Mon Sep 17 00:00:00 2001 From: Giovani Date: Mon, 21 Jul 2025 21:49:01 +0000 Subject: [PATCH] feat: add endpoints to shorten url --- main.py | 28 +++++++++++++++++++++++----- models.py | 4 ++++ utils.py | 6 ++++++ 3 files changed, 33 insertions(+), 5 deletions(-) create mode 100644 models.py create mode 100644 utils.py diff --git a/main.py b/main.py index 9867437..095f618 100644 --- a/main.py +++ b/main.py @@ -1,9 +1,27 @@ from fastapi import FastAPI +from .models import UrlPayload +from .utils import generate_shortcode app = FastAPI() -@app.get("/") -def read_root(): - return { - "Hello": "World" - } \ No newline at end of file +# temporary data store +url_mapping = {} + +@app.get("/{shortcode}") +async def get_original_url(shortcode: str): + if shortcode in url_mapping: + return {"original_url": url_mapping[shortcode]} + else: + raise HTTPException(status_code=404, detail="Shortcode not found") + + +@app.post("/shorten/") +async def create_short_url(url_payload: UrlPayload): + original_url = url_payload.url + shortcode = generate_shortcode() + + if shortcode in url_mapping: + raise HTTPException(status_code=409, detail="Shortcode already in use") + + url_mapping[shortcode] = str(original_url) + return {"shortcode": shortcode, "original_url": original_url} \ No newline at end of file diff --git a/models.py b/models.py new file mode 100644 index 0000000..b494ee9 --- /dev/null +++ b/models.py @@ -0,0 +1,4 @@ +from pydantic import BaseModel, HttpUrl + +class UrlPayload(BaseModel): + url: HttpUrl \ No newline at end of file diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..9767ef5 --- /dev/null +++ b/utils.py @@ -0,0 +1,6 @@ +import string +import random + +def generate_shortcode(length=6) -> str: + characters = string.ascii_letters + string.digits + return ''.join(random.choice(characters) for _ in range(length)) \ No newline at end of file