feat: add endpoints to shorten url
This commit is contained in:
28
main.py
28
main.py
@@ -1,9 +1,27 @@
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
from .models import UrlPayload
|
||||||
|
from .utils import generate_shortcode
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
@app.get("/")
|
# temporary data store
|
||||||
def read_root():
|
url_mapping = {}
|
||||||
return {
|
|
||||||
"Hello": "World"
|
@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
4
models.py
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
from pydantic import BaseModel, HttpUrl
|
||||||
|
|
||||||
|
class UrlPayload(BaseModel):
|
||||||
|
url: HttpUrl
|
||||||
Reference in New Issue
Block a user