Simple URL shortener app in Python for Beginners (๐Ÿ”ฅ FastAPI Demo)

Simple URL shortener app in Python for Beginners (๐Ÿ”ฅ FastAPI Demo)

ยท

4 min read

Introduction

This is a simple url shortener application developed in Python FastAPI.
Click here to access the Github repo.
Click here to access Postman API collection.

In this tutorial we will focus mainly on 3 things

  • It's beginner friendly.
  • Focused on industry best practices.
  • Deploy to cloud.

The scope of this tutorial is to focus mostly on building APIs rather than Python basics. If you're completely new to Python I would highly encourage you to have a strong knowledge on Python basics before going into this article.

Prerequisites

  • Download and install VS code from here
  • Download and install Python from here

    What is a Virtual environment ?

    A virtual environment is an isolated environment used to keep your project dependencies independently from any other projects or system configurations. This helps to avoid dependency conflicts with different versions.

Live demo

Click here to test live endpoints

Develop url shortener APIs

Setup

  • Open the VS code and create a new file named main.py in the root folder.
  • This main.py file is responsible for running your application and acts as an entry point for your app.
  • Create a Python virtual environment using this command python -m venv virtual_env_name
  • Activate your virtual environment with respective operating system commands.
# Linux
source virtual_env_name/bin/activate

# Windows
virtual_env_name\Scripts\activate.bat

#Mac
source virtual_env_name/bin/activate
  • Install all the required dependencies in the Python virtual environment.
# add fast api package
pip install fastapi

# add web server for running fast api
pip install "uvicorn[standard]"

# add package for cleaning cache files
pip install pyclean
  • Add below snippet to the main.py file. This snippet has two endpoints of request method type GET. One endpoint returns {"hello" : "world"} json response and other returns the dynamic parameter you passed as item_id
  • Run the application using the below command. The default host url is http://localhost:8000
uvicorn main:app --reload
  • Open the default endpoint and if you see something like this, then you have successfully ๐Ÿ”ฅ deployed your application locally. sample-fastapi-url.PNG
  • Similar to GET methods you can define any supported request methods you need.
  • Remove the two methods you have added i.e read_root, read_item and it's finally time to implement the actual url shortener endpoints.

Create url shortener endpoints.

  • Create the below files and directories in the root folder.
# folder : 
url_shortener

# files
url_shortener/__init__.py
url_shortener/database.py
url_shortener/router.py
url_shortener/models.py
  • __init__.py file is used for representing the current folder as a package. So that it can be referenced in other packages.
  • router.py file is responsible for handling url shortener routes.
  • models.py is a common file for defining all the necessary models for url shorteners.
  • database.py file is responsible for handling database operations. Since there are hundreds of database options available on the internet and for the purpose of simplicity, here we mimic database operations with sleep commands and store the data in memory variables.

    Define models

  • Below is the snippet for models.py. As you can see in the code, It has 2 models.
  • CreateUrlShortener model is responsible for validating creation of short URLs.
  • CreateUrlShortenerResponse model is used as a json response model.

    Define database operations

  • Below is the snippet for the database.py file. It has a member variable all_data which stores all the data in memory. Here you can define your respective database instance instead of the in memory variable. As well as it has 3 functions for creating a short url, deleting a short url and fetching all the short urls.
  • This snippet has well defined comments to help you understand the logic in detail.

    Create endpoints

  • Here is the snippet for the router.py file.
  • In this we have defined an api router named url_shortener and database instance named mock_db_operations.
  • url_shortener is used for mounting these endpoints to the main router.
  • mock_db_operations is used for performing db operations.
  • It has 3 methods defined for creating, deleting, listing endpoints and 1 method for testing url redirects in action. Use the inline comments to understand the logic in detail.

    Update main file

  • Below is the snippet for the main.py file which has the url router mounted i.e url_shortener.

Run the application locally using below command

uvicorn main:app --reload
  • Use this postman collection as API specs and test the endpoints.
  • Below are the few snapshots of API requests and responses in action using Postman.

    Create url shortener snapshot

    create-short-url.PNG

    List all short urls

    list-short-urls.PNG

    Test redirects in action

    test-redirect.PNG

    Delete short URLs

    delete-short-url.PNG

    Deploy to Cloud

    Know how to deploy this repo to Heroku ? Click here to find out right way

    Summary

    Awesome ๐Ÿ”ฅ, you have successfully completed this tutorial. I would ๐Ÿ’ to hear your feedback and comments on the great things you're gonna build with this. If you are struck somewhere feel free to comment. I am always available.
    Please find the complete code at github

Did you find this article valuable?

Support Rahul Yarragodula by becoming a sponsor. Any amount is appreciated!

ย