Simple URL shortener app in Python for Beginners (🔥 FastAPI Demo)
Tags: fastapi, python, crud, webdev
Published: 2022-06-15 18:09:42

## Introduction
This is a simple url shortener application developed in Python FastAPI.  
[Click here](https://github.com/rahul-yr/learn-fastapi-simple-url-shortner) to access the Github repo.  
[Click here](https://www.postman.com/rahul-public/workspace/fastapi-simple-url-shortner-crud/collection/8974578-e4dd76aa-0334-47c3-ba64-c84e27ff58f6) 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](https://code.visualstudio.com/download)
- Download and install Python from [here](https://www.python.org/downloads/)

## 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](https://learn-fastapi-url-shortener.herokuapp.com/url-shortener/list)

{% embed https://youtu.be/_pl0OpmZ2Og %}

## 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`
{% embed https://gist.github.com/rahul-yr/c25764f8efec05716fab15e436fc62a4 %}

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1qvjmt0rt7xm9tduz8tu.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.
{% embed https://gist.github.com/rahul-yr/7588c7a053ce15b31795e004063e3014 %}

### 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.
{% embed https://gist.github.com/rahul-yr/8d460df41bc4c3f412da936455cd7ae4 %}

### 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.
{% embed https://gist.github.com/rahul-yr/70c1a305f5fba52ba9df78ae8f95270b %}

### Update main file
- Below is the snippet for the `main.py` file which has the url router mounted i.e `url_shortener`.
{% embed https://gist.github.com/rahul-yr/fbe26707e18d778008f8d00552da492a %}

## Run the application locally using below command

```
uvicorn main:app --reload
``` 
- Use [this postman collection](https://www.postman.com/rahul-public/workspace/fastapi-simple-url-shortner-crud/collection/8974578-e4dd76aa-0334-47c3-ba64-c84e27ff58f6) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x21k6jla3r2jf7xf12m6.PNG)

### List all short urls
![list-short-urls.PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kvnqo96mgubruqf31h3d.PNG)

### Test redirects in action

![test-redirect.PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wjgwojpxvj17yu9eokcw.PNG)

### Delete short URLs
![delete-short-url.PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/au5j7wi81k0xhldl54xt.PNG)

## Deploy to cloud
Know how to deploy this repo to Heroku ? [Click here to find out right way](https://dev.to/rahulyr/how-to-deploy-any-backend-to-heroku-easily--22mf)

## 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](https://github.com/rahul-yr/learn-fastapi-simple-url-shortner)