🔧 AI Nachrichten Court Filings In A.I. Suit Invoke Copyright Law, Culture and Sports(05.09.2026 um 02:18 Uhr)
📰 IT NachrichtenHow to Check if T-Mobile Fiber Is Available at Your Address(11.09.2026 um 19:12 Uhr)
🔧 AI Nachrichten Etzioni on AI: What kids tell chatbots, but not you(04.09.2026 um 16:05 Uhr)
🔧 AI Nachrichten Court Filings In A.I. Suit Invoke Copyright Law, Culture and Sports(05.09.2026 um 02:18 Uhr)
📰 IT NachrichtenHow to Check if T-Mobile Fiber Is Available at Your Address(11.09.2026 um 19:12 Uhr)
🔧 AI Nachrichten Etzioni on AI: What kids tell chatbots, but not you(04.09.2026 um 16:05 Uhr)

🔧 Programmierung 🕛 vor 2 Jahren 4 Min Lesezeit
0

Creating a URL Shortener with FastAPI, ReactJs and TailwindCSS

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

In this article, we'll create a URL Shortener using FastAPI for the backend and ReactJs and TailwindCSS for the frontend design.



This code is a simple implementation of a URL shortening service using the FastAPI framework in Python. Let's break down the code and understand its functionality:






Backend with FastAPI



First create a virtual environment and install the dependencies




CODE
python -m venv env
source env
/bin/activate
python -m pip install fastapi uvicorn






Then, let's import the necessary imports needed




CODE
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
import secrets






Next, create a FastAPI instance:




CODE
app = FastAPI()






Next, define a Pydantic model for the request payload:




CODE
class URLItem(BaseModel):
original_url: str






Next, we'll use the in-memory database to store the mapping between the short URL and the original URL




CODE
url_database = {}






Next, let's configure the CORS middleware




CODE
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)






Next, let's create an endpoint for shortening a URL




CODE
@app.post("/shorten/")
def shorten_url(url_item: URLItem):
# Generate a short URL using secrets module
short_url = secrets.token_urlsafe(6)

# Store the mapping between short URL and original URL in the database
url_database[short_url] = url_item.original_url

# Return the short URL in the response
return {"short_url": short_url}






Finally, create an endpoint for redirecting to the original URL based on the short URL




CODE
@app.get("/{short_url}")
def redirect_to_original(short_url: str):
# Retrieve the original URL from the database
original_url = url_database.get(short_url)

# If the original URL exists, redirect to it
if original_url:
return RedirectResponse(url=original_url)
else:
# If the short URL is not found in the database, return an error response
return {"error": "URL not found"}






Run uvicorn main:app --reload to run the backend






Frontend with ReactJS



Create a Vite project and install dependencies including axios




CODE
npm init vite@latest url-shortener --template react
cd url-shortener
npm install && npm install axios






Import the useState hook from React to manage the components state and the axios library to make HTTP Requests




CODE
import { useState } from 'react';
import axios from 'axios';






The component uses the useState hook to manage state variables for the original URL (originalUrl), the shortened URL (shortUrl), and a loading indicator (loading).




CODE
const ShortenerForm = () => {
// State variables for the original URL, short URL, and loading state
const [originalUrl, setOriginalUrl] = useState('');
const [shortUrl, setShortUrl] = useState('');
const [loading, setLoading] = useState(false);






This function is called when the user clicks the "Shorten URL" button. It first checks if the original URL is provided and shows an alert if not. If the URL is valid, it sets the loading state to true, sends a POST request to the specified URL shortening service, and updates the state with the shortened URL. Any errors that occur during the process are logged, and the loading state is reset to false regardless of success or failure.




CODE
const shortenUrl = async () => {
if (!originalUrl) {
alert('Please enter a URL.');
return;
}

setLoading(true);

try {
// Making a POST request to a URL shortening service
const response = await axios.post('http://localhost:8000/shorten/', {
original_url: originalUrl,
});
// Updating state with the shortened URL
setShortUrl(`http://localhost:8000/${response.data.short_url}`);
} catch (error) {
console.error('Error shortening URL:', error);
} finally {
setLoading(false);
}
};






The render method returns JSX that defines the component's UI. It includes a form with an input field for the original URL, a button to trigger URL shortening, and a display area for the shortened URL.




CODE
return (
<div className="flex items-center justify-center h-screen">
{/* ... */}
{/* HTML form with input, button, and display for shortened URL */}
</div>
);






The component is exported as the default export, making it available for use in other parts of the application.




CODE
export default ShortenerForm;






Now run npm run dev to see the frontend



and the site can be seen at https://urlshrtnr.vercel.app/

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
1 Quelle
OpenAI Targets Work of Wall Street Junior Bankers
1 Quelle
Anthropic Reveals Rogue AI Agents Hate CAPTCHAs
1 Quelle
UK Government Rejects 'Kill Switch' Idea For Dangerous AI
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Creating a URL Shortener with FastAPI, ReactJs and TailwindCSS

Thematisch verwandte Begriffe: Creating, Shortener, with, FastAPI · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...