Hi ππ
Today i will share with you how to Create a URL shortener API using FastAPI and Python.
I will use simple ways as much as I can.
I will use JSON as a database file; you can use anything else if you want; it's up to you. I prefer using JSON because it's very easy to use and setup.
Now lit's create a JOSN file
{
"urls" : [
]
}
We didn't add the number of clicks because I wanted to make it simple and easy, and counting the number of clicks requires more advanced things, like adding admins, users, and API keys.
Now i will create the API π
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from secrets import token_urlsafe
from pydantic import BaseModel
import json
import validators
app = FastAPI()
database = json.load(open('database.json', 'r'))
class Url(BaseModel):
url : str
@app.get('/')
def home():
return {'msg': 'Welcome in My API :)'}
@app.post('/short_url')
def short_url(url : Url):
if validators.url(url.url):
url_id = token_urlsafe(5)
shorted_url = f'http://127.0.0.1:8000/{url_id}'
database['urls'].append({
'url_id': url_id,
'short_url': shorted_url,
'target_url': url.url
})
json.dump(database, open('database.json', 'w'), indent = 4)
return {'msg': 'done', 'url': shorted_url}
return {'msg': 'Invalled url'}
@app.get('/{_id}')
def get_target_url(_id: str):
for url in database['urls']:
if url['url_id'] == _id:
return RedirectResponse(url['target_url'])
return {'msg': 'Url not found :('}
Test the API
import requests
data = {
'url': 'https://dev.to/amr2018/create-quotes-api-using-fastapi-and-python-f12'
}
res = requests.post('http://127.0.0.1:8000/short_url', json=data)
print(res.json())
result
{'msg': 'done', 'url': 'http://127.0.0.1:8000/z4aKmMU'}
Open this url : http://127.0.0.1:8000/z4aKmMU
result
Now we're done π€
Don't forget to like and follow π
Support me on PayPal π€
https://www.paypal.com/paypalme/amr396