give me fastapi todo app
- User
give me fastapi todo app
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
give me fastapi todo app
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a complete FastAPI Todo application with CRUD operations, database integration using SQLAlchemy, and Pydantic models.
todo_app/
├── main.py
├── models.py
├── schemas.py
├── database.py
└── requirements.txt
First, create a requirements.txt file:
fastapi
uvicorn
sqlalchemy
pydantic
python-dotenv
Install them with:
pip install -r requirements.txt
database.py)from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./todos.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
models.py)from sqlalchemy import Column, Integer, String, Boolean
from database import Base
class Todo(Base):
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(100))
description = Column(String(500))
completed = Column(Boolean, default=False)
schemas.py)from pydantic import BaseModel
class TodoBase(BaseModel):
title: str
description: str | None = None
completed: bool = False
class TodoCreate(TodoBase):
pass
class Todo(TodoBase):
id: int
class Config:
orm_mode = True
main.py)from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
import models
import schemas
from database import SessionLocal, engine
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/todos/", response_model=schemas.Todo)
def create_todo(todo: schemas.TodoCreate, db: Session = Depends(get_db)):
db_todo = models.Todo(**todo.dict())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@app.get("/todos/", response_model=List[schemas.Todo])
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
todos = db.query(models.Todo).offset(skip).limit(limit).all()
return todos
@app.get("/todos/{todo_id}", response_model=schemas.Todo)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
todo = db.query(models.Todo).filter(models.Todo.id == todo_id).first()
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return todo
@app.put("/todos/{todo_id}", response_model=schemas.Todo)
def update_todo(todo_id: int, todo: schemas.TodoCreate, db: Session = Depends(get_db)):
db_todo = db.query(models.Todo).filter(models.Todo.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
for field, value in todo.dict().items():
setattr(db_todo, field, value)
db.commit()
db.refresh(db_todo)
return db_todo
@app.delete("/todos/{todo_id}")
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
todo = db.query(models.Todo).filter(models.Todo.id == todo_id).first()
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
db.delete(todo)
db.commit()
return {"message": "Todo deleted successfully"}
Start the server with:
uvicorn main:app --reload
/todos/ - Create a new todo/todos/ - List all todos/todos/{todo_id} - Get a specific todo/todos/{todo_id} - Update a todo/todos/{todo_id} - Delete a todoYou can test the API using curl or any API client like Postman:
curl -X POST "http://localhost:8000/todos/" -H "Content-Type: application/json" -d '{"title":"Buy groceries","description":"Milk, eggs, bread"}'
curl "http://localhost:8000/todos/"
curl "http://localhost:8000/todos/1"
curl -X PUT "http://localhost:8000/todos/1" -H "Content-Type: application/json" -d '{"title":"Buy groceries","description":"Milk, eggs, bread, cheese","completed":true}'
curl -X DELETE "http://localhost:8000/todos/1"
This provides a complete, functional Todo application with FastAPI that you can extend with additional features as needed.