التخطي إلى المحتوى الرئيسي

Create a URL shortener API using FastAPI and Python

 


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 🤗

Get the code from dev.to

تعليقات

المشاركات الشائعة من هذه المدونة

password cracker script v2 with Rockyou.txt

  Download the code from here

File changes detector Detect new and deleted files using python

  Discover how to detect new and deleted files using a simple Python script. Our video tutorial guides you through the process, making file changes detection easy for everyone. Stay tuned to enhance your Python  skills and efficiently manage your files Get code from GitHub