~3m2:05:44
Tech With Tim

Learn Fast API With This ONE Project

Oct 30, 2025

Read: ~3m · You save: 123 min

Learn FastAPI with a Single Project

Build a full-stack web app with FastAPI! From basics to auth, databases, and media uploads. A step-by-step guide on a real project.

This article describes the process of developing the backend for a photo and video sharing application using the FastAPI framework. The project covers the full API development cycle, including basic data operations, database connection, file upload handling, and user authentication implementation. Basic Python experience is assumed.

Introduction

The project's goal is to create a fully functional API for an application that allows users to upload and view photos and videos. During development, key concepts of web applications and APIs will be covered, as well as practical implementation aspects using modern tools.

Core Concepts of Web Applications and APIs

URLs, Paths, and Endpoints

URL (Uniform Resource Locator) is the address of a resource on the network. It consists of several components:

  • Scheme: The data transfer protocol (e.g., http, https).
  • Domain: The server name or IP address (e.g., example.com).
  • Path: Specifies a particular resource or page on the server (e.g., /users/profile). The path defines an endpoint—an API entry point that the client accesses.

Query Parameters

Query parameters are appended to a URL after a question mark (?) and are used to filter or refine data. They are key-value pairs separated by an ampersand (&). Example: /posts?category=technology&sort=date

Request and Response Structure

Interaction between a client (e.g., a web browser or mobile application) and a server occurs through requests and responses.

Request:

  • HTTP Method: Defines the action the client wants to perform on a resource. Main methods:
    • GET: Retrieve data.
    • POST: Create a new resource.
    • PUT/PATCH: Update an existing resource.
    • DELETE: Delete a resource.
  • Path: The API endpoint.
  • Headers: Contains request metadata, such as content type, authentication information (e.g., JWT token).
  • Body: Contains data sent to the server (e.g., form data, JSON object). Used with POST, PUT, PATCH methods.

Response:

  • Status Code: A three-digit number indicating the result of request processing. Most common:
    • 200 OK: Successful request.
    • 201 Created: Resource successfully created.
    • 204 No Content: Successful request, but no response body.
    • 400 Bad Request: Invalid client request.
    • 401 Unauthorized: Authentication required.
    • 403 Forbidden: Access denied.
    • 404 Not Found: Resource not found.
    • 500 Internal Server Error: Server-side error.
  • Headers: Response metadata, e.g., content type.
  • Body: Data returned by the server (often in JSON format).

Project Setup and Dependency Installation

To get started, you need to initialize the project and install the necessary libraries. It is recommended to use the uv package manager (or pip).

  1. Project Initialization:

    uv init .
    

    This command creates the pyproject.toml file for managing project dependencies.

  2. Dependency Installation:

    uv add fastapi uvicorn python-dotenv sqlalchemy fastapi-users imagekit-io aiosqlite
    
    • fastapi: The main framework.
    • uvicorn: An ASGI server for running FastAPI applications.
    • python-dotenv: For loading environment variables from a .env file.
    • sqlalchemy: An ORM for working with databases.
    • fastapi-users: A library for quickly implementing user authentication.
    • imagekit-io: SDK for integration with the ImageKit service for media file processing.
    • aiosqlite: An asynchronous driver for working with SQLite.
  3. Environment Variables: Create a .env file in the project root to store sensitive data, such as ImageKit API keys.

    IMAGEKIT_PRIVATE_KEY=your_private_key
    IMAGEKIT_PUBLIC_KEY=your_public_key
    IMAGEKIT_URL_ENDPOINT=your_url_endpoint
    

    You need to register on ImageKit and obtain the corresponding keys.

FastAPI Fundamentals

Creating an Application Instance

The main application file (e.g., app/main.py or app/app.py) starts by importing FastAPI and creating an application instance.

# app/app.py
from fastapi import FastAPI

app = FastAPI()

Defining Endpoints

Endpoints are defined using decorators corresponding to HTTP methods.

# app/app.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}
  • @app.get("/"): Defines a GET endpoint at the root path.
  • @app.get("/items/{item_id}"): Defines a GET endpoint with a path parameter item_id. FastAPI automatically converts item_id to int and performs validation.
  • q: str | None = None: Defines an optional query parameter q of type str.

Running the Application

The application is run using the uvicorn ASGI server. Create a main.py file to start the server.

# main.py
import uvicorn
from app.app import app # Import the FastAPI instance from app/app.py

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)

Run using:

uvicorn main:app --reload

or

uv run main.py

Automatic Documentation

FastAPI automatically generates interactive API documentation based on the code.

  • Swagger UI: /docs
  • ReDoc: /redoc

Creating the API: Core Functionality

Data Models and Schemas (Pydantic)

Pydantic is used to define data schemas, which ensure validation of incoming and outgoing data.

# app/schemas.py
from pydantic import BaseModel
from typing import Optional

class PostBase(BaseModel):
    title: str
    content: str

class PostCreate(PostBase):
    pass

class Post(PostBase):
    id: int # Or UUID if used

    class Config:
        orm_mode = True # For working with SQLAlchemy models

Path and Query Parameters

  • Path Parameters: Dynamic URL segments.
    @app.get("/posts/{post_id}")
    async def get_post(post_id: int):
        # Logic to retrieve post by ID
        return {"post_id": post_id}
    
  • Query Parameters: Optional or required parameters after ?.
    @app.get("/posts")
    async def get_posts(limit: int = 10, skip: int = 0):
        # Logic to retrieve a list of posts with filtering
        return {"limit": limit, "skip": skip}
    

Request Body

To send data in the request body (e.g., when creating a post), a Pydantic schema is used.

# app/app.py
from fastapi import FastAPI
from app.schemas import PostCreate, Post
from typing import List

app = FastAPI()

# Temporary data storage (will be replaced by a database)
posts_db = {}
post_id_counter = 1

@app.post("/posts", response_model=Post)
async def create_post(post: PostCreate):
    global post_id_counter
    new_post = Post(id=post_id_counter, title=post.title, content=post.content)
    posts_db[post_id_counter] = new_post
    post_id_counter += 1
    return new_post

Output Data Typing

Specifying the return type improves documentation and validation.

# app/app.py
from app.schemas import PostCreate, Post
from typing import List

# ... (previous code)

@app.post("/posts", response_model=Post)
async def create_post(post: PostCreate):
    # ... (post creation logic)
    return new_post

@app.get("/posts", response_model=List[Post])
async def get_all_posts():
    return list(posts_db.values())

Database Integration (SQLAlchemy & AsyncIO)

SQLite database with asynchronous access is used for persistent data storage.

Database Setup

Create a file app/db.py to configure the connection and data models.

# app/db.py
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, ForeignKey, Boolean
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.ext.asyncio import async_sessionmaker
from datetime import datetime
import uuid
from fastapi import Depends # Added for get_user_db

DATABASE_URL = "sqlite+aiosqlite:///./test.db"

# Create an asynchronous engine
engine = create_async_engine(DATABASE_URL, echo=True)

# Create an asynchronous session factory
AsyncSessionLocal = async_sessionmaker(
    autocommit=False,
    autoflush=False,
    class_=AsyncSession
)

# Base class for declarative models
Base = declarative_base()

# Data model for a post
class Post(Base):
    __tablename__ = "posts"

    id = Column(Integer, primary_key=True, index=True) # Or UUID
    title = Column(String, index=True)
    content = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)
    user_id = Column(Integer, ForeignKey("users.id")) # Relation to user
    file_url = Column(String) # URL to the media file
    file_type = Column(String) # 'image' or 'video'
    file_name = Column(String) # Original or generated filename

    user = relationship("User", back_populates="posts")

# Data model for a user (for FastAPI-Users)
class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True) # Or UUID
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)
    is_superuser = Column(Boolean, default=False)
    is_verified = Column(Boolean, default=False)

    posts = relationship("Post", back_populates="user")

# Function to get an asynchronous session
async def get_async_session() -> AsyncSession:
    async with AsyncSessionLocal() as session:
        yield session

# Function to create tables
async def create_db_tables():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

# For FastAPI-Users
from fastapi_users.db import SQLAlchemyUserDatabase
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
    yield SQLAlchemyUserDatabase(session, User)

Integration with FastAPI

Use lifespan for automatic table creation when the application starts.

# app/app.py
from fastapi import FastAPI, Depends, HTTPException, File, UploadFile, Form
from app.schemas import PostCreate, Post, UserCreate, UserRead, UserUpdate, PostWithUser # Import user schemas
from app.db import Post as PostModel, User as UserModel, get_async_session, create_db_tables, get_user_db # Import DB models
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import Session
from sqlalchemy import select
from contextlib import asynccontextmanager
from typing import List, Optional
import shutil
import os
import uuid

# Import for ImageKit
from imagekitio import ImageKit
from imagekitio.models.models import UploadFileRequestOptions
from dotenv import load_dotenv

load_dotenv() # Load environment variables

# Initialize ImageKit
imagekit = ImageKit(
    private_key=os.getenv("IMAGEKIT_PRIVATE_KEY"),
    public_key=os.getenv("IMAGEKIT_PUBLIC_KEY"),
    url_endpoint=os.getenv("IMAGEKIT_URL_ENDPOINT")
)

# --- User Authentication (FastAPI-Users) ---
from fastapi_users import FastAPIUsers, BaseUserManager, UUID_ID
from fastapi_users.authentication import (
    AuthenticationBackend,
    BearerTransport,
    JWTStrategy,
)
from fastapi_users.db import SQLAlchemyUserDatabase

# JWT secret key (should be strong and stored in .env)
SECRET = os.getenv("JWT_SECRET_KEY", "your_super_secret_key_here") # Recommended to generate a random key

# User Manager
class UserManager(BaseUserManager[UUID_ID, UserModel]):
    reset_password_token_secret = SECRET
    verification_token_secret = SECRET

async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
    yield UserManager(user_db)

# Token transport (Bearer Token)
bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")

# JWT Strategy
def get_jwt_strategy() -> JWTStrategy:
    return JWTStrategy(secret=SECRET, lifetime_seconds=3600) # Token valid for 1 hour

# Authentication Backend
auth_backend = AuthenticationBackend(
    name="jwt",
    transport=bearer_transport,
    get_strategy=get_jwt_strategy,
)

fastapi_users = FastAPIUsers[UserModel, UUID_ID](
    get_user_manager, auth_backend
)

# Get current active user
current_active_user = fastapi_users.current_user(active=True)

# --- Application Lifecycle Context Manager ---
@asynccontextmanager
async def lifespan(app: FastAPI):
    await create_db_tables() # Create tables on startup
    yield

app = FastAPI(lifespan=lifespan)

# --- Include Authentication Routes ---
app.include_router(
    fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
)
app.include_router(
    fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"]
)
app.include_router(
    fastapi_users.get_reset_password_router(), prefix="/auth", tags=["auth"]
)
app.include_router(
    fastapi_users.get_verify_router(), prefix="/auth", tags=["auth"]
)
app.include_router(
    fastapi_users.get_users_router(), prefix="/users", tags=["users"]
)

# --- API Endpoints ---

# Get current user (protected endpoint)
@app.get("/users/me", response_model=UserRead)
async def read_users_me(current_user: UserModel = Depends(current_active_user)):
    return current_user

# Get all posts (protected endpoint)
@app.get("/feed", response_model=List[PostWithUser])
async def get_feed(
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user) # Authentication required
):
    # Query posts with user information
    stmt = select(PostModel).order_by(PostModel.created_at.desc())
    result = await session.execute(stmt)
    posts = result.scalars().all()

    # Format response with user info and owner status
    posts_data = []
    for post in posts:
        is_owner = (post.user_id == current_user.id)
        posts_data.append(PostWithUser(
            id=post.id,
            title=post.title,
            content=post.content,
            created_at=post.created_at,
            user_id=post.user_id,
            file_url=post.file_url,
            file_type=post.file_type,
            file_name=post.file_name,
            is_owner=is_owner,
            user_email=post.user.email if post.user else "Unknown"
        ))
    return posts_data

# Upload file (photo/video) and create a post (protected endpoint)
@app.post("/upload", response_model=PostWithUser)
async def upload_file(
    file: UploadFile = File(...),
    caption: str = Form(...),
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user) # Authentication required
):
    # Generate unique filename
    file_extension = os.path.splitext(file.filename)[1]
    unique_filename = f"{uuid.uuid4()}{file_extension}"

    # Upload file to ImageKit
    try:
        upload_result = imagekit.upload_file(
            file=file.file,
            file_name=unique_filename,
            options=UploadFileRequestOptions(
                use_unique_file_name=True,
                tags=["backend_upload"],
                folder="uploads" # Optional: folder in ImageKit
            )
        )
        file_url = upload_result.url
        file_type = "video" if file.content_type.startswith("video/") else "image"
        file_name = upload_result.name

        # Create a new post in the database
        new_post = PostModel(
            title=caption, # Use caption as title
            content=caption, # Or add a separate content field
            user_id=current_user.id,
            file_url=file_url,
            file_type=file_type,
            file_name=file_name
        )
        session.add(new_post)
        await session.commit()
        await session.refresh(new_post)

        # Return post data, including URL and user info
        return PostWithUser(
            id=new_post.id,
            title=new_post.title,
            content=new_post.content,
            created_at=new_post.created_at,
            user_id=new_post.user_id,
            file_url=new_post.file_url,
            file_type=new_post.file_type,
            file_name=new_post.file_name,
            is_owner=True, # New post always belongs to the current user
            user_email=current_user.email
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"File upload failed: {e}")

# Delete post (protected endpoint)
@app.delete("/posts/{post_id}", response_model=dict)
async def delete_post(
    post_id: int,
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user) # Authentication required
):
    # Get post from database
    stmt = select(PostModel).where(PostModel.id == post_id)
    result = await session.execute(stmt)
    post = result.scalars().first()

    if not post:
        raise HTTPException(status_code=404, detail="Post not found")

    # Check permissions: only the post author can delete it
    if post.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="You do not have permission to delete this post")

    # Delete post from database
    await session.delete(post)
    await session.commit()

    return {"message": "Post deleted successfully"}

# --- Additional User Schemas ---
# These schemas inherit from standard FastAPI-Users schemas
# but can be extended if needed.
from fastapi_users import schemas

class UserRead(schemas.BaseUser[uuid.UUID]):
    email: str
    is_active: bool = True
    is_superuser: bool = False
    is_verified: bool = False
    id: uuid.UUID # Ensure ID matches the type in the DB model

class UserCreate(schemas.BaseUserCreate):
    password: str
    email: str
    is_active: bool = True
    is_superuser: bool = False
    is_verified: bool = False

class UserUpdate(schemas.BaseUserUpdate):
    password: Optional[str] = None
    email: Optional[str] = None
    is_active: Optional[bool] = None
    is_superuser: Optional[bool] = None
    is_verified: Optional[bool] = None

# Update Post model to include user info and owner status
class PostWithUser(Post):
    user_id: Optional[int] # Or UUID
    file_url: str
    file_type: str
    file_name: str
    is_owner: bool
    user_email: str

# Update get_feed endpoint to return PostWithUser
@app.get("/feed", response_model=List[PostWithUser])
async def get_feed(
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user)
):
    stmt = select(PostModel).order_by(PostModel.created_at.desc())
    result = await session.execute(stmt)
    posts = result.scalars().all()

    posts_data = []
    for post in posts:
        is_owner = (post.user_id == current_user.id)
        posts_data.append(PostWithUser(
            id=post.id,
            title=post.title,
            content=post.content,
            created_at=post.created_at,
            user_id=post.user_id,
            file_url=post.file_url,
            file_type=post.file_type,
            file_name=post.file_name,
            is_owner=is_owner,
            user_email=post.user.email if post.user else "Unknown"
        ))
    return posts_data

# Update upload_file endpoint to return PostWithUser
@app.post("/upload", response_model=PostWithUser)
async def upload_file(
    file: UploadFile = File(...),
    caption: str = Form(...),
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user)
):
    file_extension = os.path.splitext(file.filename)[1]
    unique_filename = f"{uuid.uuid4()}{file_extension}"

    try:
        upload_result = imagekit.upload_file(
            file=file.file,
            file_name=unique_filename,
            options=UploadFileRequestOptions(
                use_unique_file_name=True,
                tags=["backend_upload"],
                folder="uploads"
            )
        )
        file_url = upload_result.url
        file_type = "video" if file.content_type.startswith("video/") else "image"
        file_name = upload_result.name

        new_post = PostModel(
            title=caption,
            content=caption,
            user_id=current_user.id,
            file_url=file_url,
            file_type=file_type,
            file_name=file_name
        )
        session.add(new_post)
        await session.commit()
        await session.refresh(new_post)

        return PostWithUser(
            id=new_post.id,
            title=new_post.title,
            content=new_post.content,
            created_at=new_post.created_at,
            user_id=new_post.user_id,
            file_url=new_post.file_url,
            file_type=new_post.file_type,
            file_name=new_post.file_name,
            is_owner=True, # New post always belongs to the current user
            user_email=current_user.email
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"File upload failed: {e}")

# Update Post model to include ForeignKey and relationship
# In app/db.py:
# Add to Post class:
# user_id = Column(Integer, ForeignKey("users.id"))
# user = relationship("User", back_populates="posts")
# Add to User class:
# posts = relationship("Post", back_populates="user")
# Ensure User and Post inherit from Base and have corresponding fields.
# Also, update Pydantic schemas (PostCreate, Post, UserRead, UserCreate, UserUpdate)
# and ensure they match SQLAlchemy models.

File Uploads with ImageKit

Integration with ImageKit allows for easy media file management.

  1. ImageKit Initialization: In app/app.py, import and initialize the ImageKit client using keys from .env.

  2. Upload Handling: The /upload endpoint accepts UploadFile and caption from a form. The file is uploaded to ImageKit, and the obtained URL is saved to the database along with post and user information.

    # In app/app.py
    from fastapi import File, UploadFile, Form
    # ... (other imports)
    
    @app.post("/upload", response_model=PostWithUser)
    async def upload_file(
        file: UploadFile = File(...),
        caption: str = Form(...),
        session: AsyncSession = Depends(get_async_session),
        current_user: UserModel = Depends(current_active_user)
    ):
        # ... (logic for uploading to ImageKit and saving to DB)
        pass
    

Media Transformations

ImageKit allows applying transformations to images and videos directly via URL. For example, resizing, adding text, applying effects.

Example URL with transformations: https://ik.imagekit.io/your_public_key/your_file_name.jpg?tr=w-300,h-200,fo-auto

Authentication and Authorization (FastAPI-Users)

FastAPI-Users simplifies the implementation of user authentication using JWT (JSON Web Tokens).

JWT Concept

JWT is a standard for securely transmitting information between parties as a JSON object. It consists of three parts: a header, a payload, and a signature. The token is signed with a server secret key, which allows its authenticity to be verified.

FastAPI-Users Setup

  1. User Models: Define the User model in app/db.py, inheriting from SQLAlchemyUserTable and including necessary fields (email, password, roles).
  2. User Schemas: Create UserRead, UserCreate, UserUpdate schemas in app/schemas.py.
  3. User Manager and Authentication Backend: Configure UserManager, BearerTransport, JWTStrategy, and AuthenticationBackend in app/app.py.
  4. Include Routers: Use app.include_router() to add standard authentication routes (registration, login, password reset).

Protecting Endpoints

To protect endpoints, add the Depends(current_active_user) dependency to the endpoint functions. If the user is not authenticated, the request will be rejected.

# app/app.py
from fastapi_users import FastAPIUsers, BaseUserManager, UUID_ID
from fastapi_users.authentication import (
    AuthenticationBackend,
    BearerTransport,
    JWTStrategy,
)
from fastapi_users.db import SQLAlchemyUserDatabase

# ... (model and schema definitions)

# Get current active user
current_active_user = fastapi_users.current_user(active=True)

@app.get("/protected-route")
async def protected_route(current_user: UserModel = Depends(current_active_user)):
    return {"message": f"Hello, {current_user.email}!"}

Authorization (Permission Checks)

When deleting a post, it's necessary to ensure the current user is the author of the post.

# app/app.py
@app.delete("/posts/{post_id}", response_model=dict)
async def delete_post(
    post_id: int,
    session: AsyncSession = Depends(get_async_session),
    current_user: UserModel = Depends(current_active_user)
):
    # ... (get post)
    if post.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="You do not have permission to delete this post")
    # ... (delete post)

Frontend (Streamlit)

A simple frontend can be created using the Streamlit library to demonstrate API functionality. Streamlit allows for rapid creation of interactive web applications in Python.

  1. Install Streamlit:

    uv add streamlit
    
  2. Create Frontend File: Create a frontend.py file with code that interacts with the API (sends requests for authentication, file uploads, feed retrieval). Frontend code typically includes:

    • Session state management (storing JWT token).
    • Functions for sending HTTP requests with the token in the header.
    • Interfaces for registration, login, file uploads, and displaying the feed.
  3. Run Streamlit:

    uv run streamlit run frontend.py
    

Conclusion

The developed application demonstrates a comprehensive approach to creating a modern web API using FastAPI. It includes request handling, database interaction, secure user authentication, and integration with external services for media file processing. The resulting API serves as a foundation for building scalable and reliable web applications.

Video Overview

Overview of the video and demonstration of the finished project.

  • Demonstration of a photo/video application.
  • Ability to log in, view feed, upload content.
  • Using Streamlit for the frontend.

Web Application Architecture and Theory

Explanation of web application architecture and core theoretical concepts.

  • Concepts of URL, domain, path (endpoint).
  • Role of query parameters.
  • Request and response structure.
  • HTTP methods: GET, POST, PUT, DELETE.
  • HTTP statuses (200, 404, etc.).

Project Setup and Installation

Setting up the development environment and installing necessary dependencies.

  • Using uv for dependency management.
  • Installing fastapi, python-dotenv, fastapi-users, sqlalchemy, imagekitio, uvicorn.
  • Creating a .env file for storing keys.

FastAPI Setup and Basics

Basic creation of a FastAPI application and setting up the first endpoint.

  • Creating a FastAPI instance.
  • Defining the /hello-world endpoint with GET method.
  • Returning a JSON response.
  • Running the server using uvicorn.
  • Using /docs for automatic documentation.

GET and Retrieving Posts

Working with endpoints to retrieve data, including path and query parameters.

  • Creating the /posts endpoint to get all posts.
  • Using path parameters (e.g., /post/{id}) to get a specific post.
  • Handling errors (HTTPException 404).
  • Using query parameters (e.g., limit) for filtering.

Request Body and POST

Implementing a POST endpoint to create new entries using Pydantic models.

  • Defining data schema using Pydantic (PostCreate).
  • Receiving data via request body.
  • FastAPI's automatic data validation.
  • Creating a new post and returning it.

Database Connection

Connecting to an SQLite database and defining data models.

  • Using SQLAlchemy for ORM.
  • Setting up an asynchronous engine create_async_engine.
  • Defining the Post model with fields id, caption, url, file_type, file_name, created_at.
  • Configuring application lifespan (lifespan) for table creation.

Image and Video Upload (ImageKit)

Implementing file upload functionality (images and videos) using ImageKit.

  • Integration with ImageKit for media storage and processing.
  • Creating temporary files for upload.
  • Using upload_file from imagekitio.
  • Saving file URL and metadata to the database.
  • Handling upload errors.

Deleting Posts

Implementing functionality to delete entries from the database.

  • Creating a DELETE endpoint /post/{post_id}.
  • Getting the post ID from the path parameter.
  • Searching for the post in the database.
  • Deleting the post and confirming the operation.

User Authentication and JWT Tokens

Setting up user authentication using JWT and FastAPI Users.

  • Using fastapi-users for user management.
  • Configuring JWT strategy and authentication backend.
  • Defining User models and relationships with Post.
  • Creating endpoints for registration, login, logout.

Securing Endpoints

Securing API endpoints so that only authenticated users have access.

  • Using Depends(current_active_user) to protect endpoints.
  • Checking access rights when deleting a post.
  • Displaying user information in the feed.
  • Using Streamlit for the frontend.

Streamlit Frontend

Creating a simple user interface using Streamlit to interact with the API.

  • Using Streamlit for UI creation.
  • Managing JWT token in the session.
  • Implementing login, registration, file upload, and feed display logic.
  • Applying ImageKit for displaying images with transformations.