feat: add endpoints to shorten url

This commit is contained in:
2025-07-21 21:49:01 +00:00
parent 7ef8cd9c90
commit 28314e3865
3 changed files with 33 additions and 5 deletions

28
main.py
View File

@@ -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"
}
# 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}

4
models.py Normal file
View File

@@ -0,0 +1,4 @@
from pydantic import BaseModel, HttpUrl
class UrlPayload(BaseModel):
url: HttpUrl

6
utils.py Normal file
View File

@@ -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))