Below is a simple working ToDo application written in Python using FastAPI, Docker, and Swagger UI. The app implements the specified API endpoints and stores data in RAM. The instructions for running the application and potential error handling are also provided.
Project Structure
todo_app/
│
├── app/
│ ├── main.py
│ ├── models.py
│ ├── schemas.py
│ └── database.py
│
├── Dockerfile
├── requirements.txt
└── docker-compose.yml
1. Create the Project Directory
Create a directory for your project:
mkdir todo_app
cd todo_app
2. Create Required Files
main.py (FastAPI main application)
from fastapi import FastAPI, HTTPException
from typing import List
from models import Task, TaskIn, TaskUpdate
from database import db
app = FastAPI()
@app.post("/tasks", response_model=Task)
def create_task(task: TaskIn):
task_id = str(len(db) + 1)
new_task = Task(ID=task_id, **task.dict())
db[task_id] = new_task
return new_task
@app.get("/tasks", response_model=List[Task])
def get_tasks():
return list(db.values())
@app.get("/tasks/{id}", response_model=Task)
def get_task(id: str):
task = db.get(id)
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return task
@app.put("/tasks/{id}", response_model=Task)
def update_task(id: str, task_update: TaskUpdate):
if id not in db:
raise HTTPException(status_code=404, detail="Task not found")
task = db[id]
updated_task = task.copy(update=task_update.dict(exclude_unset=True))
db[id] = updated_task
return updated_task
@app.delete("/tasks/{id}", response_model=dict)
def delete_task(id: str):
if id not in db:
raise HTTPException(status_code=404, detail="Task not found")
del db[id]
return {"message": "Task deleted successfully"}
models.py (Defining Task model)
from pydantic import BaseModel
from typing import Optional
from datetime import datetime
class Task(BaseModel):
ID: str
Title: str
Description: str
Done: bool
ToDo: datetime
CreatedAt: datetime
UpdatedAt: datetime
DeletedAt: Optional[datetime] = None
class TaskIn(BaseModel):
Title: str
Description: str
Done: bool
ToDo: datetime
class TaskUpdate(BaseModel):
Title: Optional[str] = None
Description: Optional[str] = None
Done: Optional[bool] = None
ToDo: Optional[datetime] = None
database.py (In-memory database)
# In-memory database
db = {}
requirements.txt (Dependencies)
fastapi
uvicorn
pydantic
Dockerfile (Docker configuration)
FROM python:3.9
WORKDIR /app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY ./app ./app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8080", "--reload"]
docker-compose.yml (Docker Compose configuration)
version: '3.8'
services:
todo_app:
build: .
ports:
- "8080:8080"
3. Build and Run the Application with Docker
- Build the Docker image and run the container:
docker-compose up --build
- Access the application:
4. Potential Errors and Troubleshooting
-
Port Conflicts: If you cannot access the application at localhost:8080, check if another application is using that port. You can either stop the conflicting application or change the port mapping in docker-compose.yml.
-
Docker Installation: Ensure you have Docker installed and running. If you're unfamiliar with Docker, refer to Docker's documentation.
-
Dependencies Issues: If there are issues installing the dependencies, make sure your Python version in the Dockerfile is compatible with the packages in requirements.txt.
5. Changing to PostgreSQL (Optional)
To switch to a PostgreSQL database, you will need to modify the database logic in database.py, install asyncpg and SQLAlchemy, and change your docker-compose.yml to include a PostgreSQL service. I can provide details on this if you wish!
This structure offers a basic, scalable, and documented API application. You can easily extend it with more complex features or connect it to a persistent database like PostgreSQL later.