How to build a URL Shortener With FastAPI and Python

URL Shortener | Coding Zemigle

Concise but shareable links are more important than ever in the broad world of the internet, because every character matters in a URL. This blog will walk you through the exciting process of creating your own URL Shortener with Python and FastAPI, a potent combinations. We'll discover the value about URL Shorteners in streamlining links and improving user experience as we set off on this adventure.

This project gives everyone the opportunity to learn more about FastAPI, a cutting edge web framework for creating Payton APIs, than just shortening URLs. You'll have a working URL Shortener and a better knowledge of of the underlying mechanisms by conclusion of this exploration. Now, let's explore the complexities of building a URL shortener from beginning of both simple and effective.


Before we go into the details of creating a URL shortener, we must first lay the groundwork for our project. This section will walk you through the first steps if creating the framework and atmosphere required for a productive development process. First, we install the dependencies for FastAPI to make sure our development environment has all the tools required for this project. In this tutorial, you'll learn how to:
  • Create a REST API with FastAPI
  • Run a developer web server with Uvicorn
  • Model a SQLite database
  • Investigate the auto-generated API documentation
  • Interact with the database with CRUD actions
  • Optimize your app by refactoring your code
We'll also investigate the best possible project structure, arranging directories files in order to preserve scalability and clarity as a URL shortener develops. As you proceed through the setup process, keep in mind that a solid foundation creates the framework for an application that is reliable and easy to maintain. We'll, let's get started and get our project ready for the thrilling development ahead.

Step 1: Setting up the URL Shortener with FastAPI

Now that our project environment is in place, we can turn our attention to developing the URL shortener's concept and design. The nuances of designing a solution that additionally shortens URLs yet also complies with our functional and user experience objectives will be discussed in this section. To get's started, let's define the data models. These will include the structures how will be used to represent URLs or their reduced versions. Make sure to install FastAPI and Uvicorn using:


pip install fastapi uvicorn
This initial stage is essential for laying the framework for the remainder of the program. The API parameters that will control user interaction with the URL Shortener will then be carefully planned. This entails giving considerable through to the user journey from entering a URL to be shortened to using the redirected links.

You'll have a detailed blueprint for your URL shortener's internal operations at the end of this part, which will prepare you for the implementation step. So let's go headfirst into the design process and carefully and strategically mold our URL shortener.

Step 2: Coding with FastAPI and Python

Now that the initial implementation has been completed, it is time to thoroughly test and debug the URL shortener to guarantee its dependability and stability. You'll be guided through the necessary steps to validate your code and find or fix any possible problems in this section. We'll get into the craft of crafting unit examinations for the web page shortener, addressing several scenarios including redirection, edge cade heading and URL shortening.

✲    script.py
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
from datetime import datetime, timedelta
from typing import Optional
import secrets

app = FastAPI()

class URLData(BaseModel):
    original_url: str
    short_url: Optional[str] = None
    expiration_date: Optional[datetime] = None

url_database = {}

def generate_short_url():
    return secrets.token_urlsafe(5)

def create_short_url(url_data: URLData):
    short_url = url_data.short_url or generate_short_url()
    expiration_date = url_data.expiration_date or None

    url_entry = {
        'original_url': url_data.original_url,
        'short_url': short_url,
        'expiration_date': expiration_date,
        'created_at': datetime.now(),
        'click_count': 0
    }

    url_database[short_url] = url_entry
    return url_entry

def get_url_data(short_url: str = Depends(generate_short_url)):
    if short_url not in url_database:
        raise HTTPException(status_code=404, detail="URL not found")
    return url_database[short_url]

@app.post("/shorten", response_model=URLData)
async def shorten_url(url_data: URLData):
    return create_short_url(url_data)

@app.get("/{short_url}")
async def redirect_url(short_url: str = Depends(get_url_data)):
    short_url_data = url_database[short_url]
    short_url_data['click_count'] += 1
    return {"original_url": short_url_data['original_url']}

@app.get("/url_info/{short_url}", response_model=URLData)
async def get_url_info(short_url: str = Depends(get_url_data)):
    return short_url

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)



Thorough testing helps to ensure that your code is correct and also makes future changes and improvements easier. An essential ability in any construction process is debugging. We'll go over typical problems that could come up while testing and offers advice on how to debug and improve your code. This repeated debugging procedure is essential to building a reliable as well as error proof URL shortener. Throughout the testing and debugging phase, pay close attention to the overall dependability for performance of your application.

Let's make sure that, despite a variety of scenarios and user interactions, our URL shortener is not only effective but also robust. Now that you're project has a strong base and a working URL Shortener, you're ready to add innovative features to expand its potential. We'll look at ways to personalize and enhance your URL shortener's features beyond its basic configuration in this section.

URL Shortener's Conclusion

During our investigation into using Python and FastAPI to create a URL shortener, we've covered planning, execution and deployment. What was once only a notion now involved into a useful tool with a ton of features that is prepared to streamlined and customised the link sharing process, when you look back on your voyage.

You've improved your testing and debugging abilities, learnt how to create and build a web address shortener and acquired insight into the potential of FastAPI. Your project has advanced beyond the fundamentals with the incorporation of of features include usage statistics and personalized short URLs. When you wrap up this project, think about how your URL shortener may contribute to the streamlining of the online environment.

Whether incorporated into bigger networks or utilize the private connections, your work is proof of your expertise with Python and FastAPI. With the newfound understanding, you're ready investigate more advances in the ever evolving field of website development, in addition to maintaining and improve your URL shortener. Congratulations on finishing this journey, and we hope our URL shortener helps uses all around the internet with efficiency and convenience.