Build a Quick FastAPI SQLite REST API in Python: CRUD Operations with SQLAlchemy in 14 Minutes

Posted by


Building a FastAPI SQLite REST API in Python with CRUD operations using SQLAlchemy can be a powerful way to create a simple and efficient web application. In this tutorial, we will walk through step by step on how to set up a FastAPI server with SQLite as the database and perform CRUD operations in just 14 minutes.

Requirements:

  1. Python installed on your machine (version 3.6+ recommended)
  2. pip (Python package installer)
  3. FastAPI and SQLAlchemy libraries

Step 1: Setting up the environment
First, create a new directory for your project and navigate to it in your terminal. Then, create a virtual environment using venv:

python -m venv env

Activate the virtual environment:

On Windows:

.envScriptsactivate

On MacOS/Linux:

source env/bin/activate

Install the required dependencies:

pip install fastapi uvicorn sqlalchemy

Step 2: Create a SQLite database
Create a new file named database.db in your project directory to store the SQLite database.

Step 3: Create a FastAPI server
Create a new file named main.py in your project directory and start setting up the FastAPI server:

from fastapi import FastAPI

app = FastAPI()

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

Run the FastAPI server using uvicorn:

uvicorn main:app --reload

Navigate to http://localhost:8000 in your browser to see the "Hello World" message.

Step 4: Set up SQLAlchemy
Create a new file named database.py in your project directory and set up the connection to the SQLite database using SQLAlchemy:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./database.db"

engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

Step 5: Create a database model
Create a new file named models.py in your project directory and define a database model using SQLAlchemy:

from sqlalchemy import Column, Integer, String
from database import Base

class Item(Base):
    __tablename__ = "items"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    description = Column(String)

Step 6: Create CRUD operations
Create a new file named crud.py in your project directory and define CRUD operations for the Item model:

from sqlalchemy.orm import Session
from models import Item

def get_items(db: Session):
    return db.query(Item).all()

def get_item(db: Session, item_id: int):
    return db.query(Item).filter(Item.id == item_id).first()

def create_item(db: Session, item: Item):
    db.add(item)
    db.commit()
    db.refresh(item)
    return item

def update_item(db: Session, item_id: int, updated_item: Item):
    item = db.query(Item).filter(Item.id == item_id).first()
    item.name = updated_item.name
    item.description = updated_item.description
    db.commit()
    db.refresh(item)
    return item

def delete_item(db: Session, item_id: int):
    item = db.query(Item).filter(Item.id == item_id).first()
    db.delete(item)
    db.commit()

Step 7: Create API endpoints
Update the main.py file to create API endpoints for CRUD operations:

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
import database
import models
import crud

app = FastAPI()

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

@app.get("/items")
def read_items(db: Session = Depends(get_db)):
    items = crud.get_items(db)
    return items

@app.get("/items/{item_id}")
def read_item(item_id: int, db: Session = Depends(get_db)):
    item = crud.get_item(db, item_id)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

@app.post("/items")
def create_item(item: models.Item, db: Session = Depends(get_db)):
    return crud.create_item(db, item)

@app.put("/items/{item_id}")
def update_item(item_id: int, updated_item: models.Item, db: Session = Depends(get_db)):
    return crud.update_item(db, item_id, updated_item)

@app.delete("/items/{item_id}")
def delete_item(item_id: int, db: Session = Depends(get_db)):
    return crud.delete_item(db, item_id)

Step 8: Test the API endpoints
Restart the FastAPI server using uvicorn and test the API endpoints using tools like Postman or curl:

uvicorn main:app --reload

You can now perform CRUD operations on the Item model using the API endpoints:

  • GET /items to retrieve all items
  • GET /items/{item_id} to retrieve a specific item
  • POST /items to create a new item
  • PUT /items/{item_id} to update an existing item
  • DELETE /items/{item_id} to delete an item

Congratulations! You have successfully built a FastAPI SQLite REST API in Python with CRUD operations using SQLAlchemy. Feel free to customize and expand on this project for your specific needs.

0 0 votes
Article Rating

Leave a Reply

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@webdesignfx
8 days ago

Best video i found on fastapi. Really appreciate it !! subscribed ❤

@eastern_european1968
8 days ago

8:21 could you like explain? I understand why we got the exception, but like what is the Config subclass in the UserResponse?

@MohamedOuabbi
8 days ago

Done

@SimoOuabbi-d7v
8 days ago

🎉🎉

@SimoOuabbi-d7v
8 days ago

Thanks 🙏🎉

5
0
Would love your thoughts, please comment.x
()
x