Build a FastAPI URL Shortener with SQLite

Zusammenfassung

Pixel shares a hands-on tutorial for building Snip, a URL shortener API with FastAPI, SQLite, SQLAlchemy, and Pydantic. It covers creating and deleting links, custom codes, click tracking, 307 redirects, and testing endpoints and errors with curl—useful skills for building lightweight web APIs.

DEV Community

Build a URL Shortener with FastAPI and SQLite

A URL shortener turns a long web address into a short code, so a link like logicstack.org/blog/build-rag-chatbot-langchain-chroma becomes 127.0.0.1:8000/AZ90EO. Short links are easier to share in chats, slides and printed material, and each one can count its own clicks. In this tutorial we build a working shortener with FastAPI and SQLite, then test every endpoint with curl. Key takeaways A short link is one database row: a code, a target URL, a click count and a timestamp. FastAPI turns a Pydantic model into request validation, so a bad URL is rejected with a 422 before our code runs. SQLAlchemy maps the links table to a Python class, and SQLite keeps the whole database in one file. A 307 redirect sends the visitor to the target and lets us count the click first. Every endpoint in this tutorial was run and checked with curl, including the error cases. What are we building? We build Snip, a small API with five endpoints. POST /links creates a short link from a long URL, with an optional custom code. GET /{code} redirects a visitor to the target and adds one to the click count. GET /links lists every link, GET /links/{code} shows the stats for one link, and DELETE /links/{code} removes a link. FastAPI describes itself as a modern, fast web framework for building APIs with Python, based on standard Python type hints (FastAPI docs). SQLite is a self-contained SQL database engine that stores a whole database in a single file (SQLite docs). That pair keeps the project small: one Python file, one database file, no separate database server. What do you need before we start? We need Python 3.12 and a virtual environment. We ran this tutorial on Python 3.12.3 with FastAPI 0.162.2, Uvicorn 0.54.0, SQLAlchemy 2.1.8 and Pydantic 2.14.3. Install the three packages, then create a project folder and a file called main.py: python -m venv .venv
source .venv/bin/activate
pip install fastapi uvicorn sqlalchemy
mkdir url-shortener && cd url-shortener
How do we store a link? Step 1 is the database layer. We create a SQLite engine, a session factory, and one table called links with four columns plus an id. The code column is unique and indexed, because every lookup runs on it. The created_at column defaults to the current time in UTC. Base.metadata.create_all builds the table the first time the file runs. import secrets
import string
from datetime import datetime, timezone

from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import RedirectResponse
from pydantic import BaseModel, HttpUrl
from sqlalchemy import Column, DateTime, Integer, String, create_engine
from sqlalchemy.orm import Session, declarative_base, sessionmaker

DATABASE_URL = "sqlite:///./shortener.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(bind=engine)
Base = declarative_base()

ALPHABET = string.ascii_letters + string.digits

class Link(Base):
tablename = "links"
id = Column(Integer, primary_key=True)
code = Column(String(10), unique=True, index=True)
target_url = Column(String(2048))
clicks = Column(Integer, default=0)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))

Base.metadata.create_all(bind=engine)

app = FastAPI(title="Snip URL Shortener")

def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

def make_code(length: int = 6) -> str:
return "".join(secrets.choice(ALPHABET) for _ in range(length))
Two details matter here. First, check_same_thread is False because FastAPI serves requests on more than one thread and SQLite normally forbids sharing a connection across threads. Second, we use the secrets module for codes, because it is designed for values that are hard to guess, unlike the random module. A six character code from 62 letters and digits gives about 56 billion possible codes, so collisions are rare and we still check for them. How do we create a short link? Step 2 is the c...
Build a FastAPI URL Shortener with SQLite
Powered by Readybot.io

Das Neueste von Pixel

Incident Response: Look Beyond the Red Alert

Pixel’s DEV Community announcement explores how teams can fixate on one failing service while overlooking the real cause of an outage, such as a full …

Sach: AI Fact-Checks WhatsApp Forwards in India

Pixel’s announcement introduces Sach, a tool that checks forwarded messages in English, Hindi, Telugu, and 14 other Indian languages against official sources. It gives cited …

Java 25 Removes SecurityManager: What to Fix

Pixel’s announcement explains how Java 24’s JEP 486 permanently disabled the SecurityManager, breaking test workarounds that intercept System.exit. It recommends returning exit codes or throwing …