Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,10 @@ jobs:
fi

- name: Install integration test dependencies
run: pip install pytest pymongo pydantic-settings
run: pip install -r backend/requirements.txt pytest httpx2

- name: Test API documentation and HTTP behavior
run: pytest tests/test_api_docs.py -v

- name: Run integration tests
env:
Expand Down
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,14 @@ Click **Open in GitHub Codespaces** above — MongoDB Atlas Local starts automat
| PUT | `/task/{id}` | Update a task |
| DELETE | `/task/{id}` | Delete a task |

Full interactive docs: `http://localhost:8000/docs`
Full interactive docs: `http://localhost:8000/docs`; OpenAPI schema:
`http://localhost:8000/openapi.json`. The Swagger UI documents request fields,
examples, responses, and errors for each endpoint. Tasks use `_id`, `name`, and
`completed`; the list endpoint returns at most 100 tasks without a guaranteed order.

**Known issue:** deleting an existing task currently removes it but may return
`500` instead of the intended empty `204` response. Check whether the task still
exists before retrying. This issue is also documented in Swagger.

## Project Structure

Expand Down Expand Up @@ -123,6 +130,10 @@ FARM-Intro/
# Runtime (no MongoDB needed)
python tests/test_runtime.py

# OpenAPI and HTTP behavior (no MongoDB needed; install pytest and httpx2)
pip install pytest httpx2
pytest tests/test_api_docs.py -v

# Integration (requires MongoDB)
MONGODB_URI="mongodb://localhost:27017/" pytest tests/test_integration.py -v
```
Expand Down Expand Up @@ -150,4 +161,3 @@ CI runs both test suites on every push using a `mongo:latest` service container
| `ModuleNotFoundError: pydantic_settings` | Run `pip install -r requirements.txt` (needs `pydantic-settings`) |
| React `npm start` fails on Node 18 | Use Node 22: `nvm use 22` |
| Frontend shows empty timeline | Backend not running or CORS issue; confirm `http://localhost:8000/task/` returns JSON |

36 changes: 27 additions & 9 deletions backend/apps/todo/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,45 @@ class TaskModel(BaseModel):
populate_by_name=True,
json_schema_extra={
"example": {
"id": "00010203-0405-0607-0809-0a0b0c0d0e0f",
"name": "My important task",
"completed": True,
"_id": "9e46475a-2ea8-4fdc-a97f-bfd57e9df932",
"name": "Buy groceries",
"completed": False,
}
},
)

id: str = Field(default_factory=lambda: str(uuid.uuid4()), alias="_id")
name: str = Field(...)
completed: bool = False
id: str = Field(
default_factory=lambda: str(uuid.uuid4()),
alias="_id",
description=(
"Task identifier. When omitted, a UUID v4 is generated. "
"It also accepts a client-provided string, without validating the UUID format."
),
examples=["9e46475a-2ea8-4fdc-a97f-bfd57e9df932"],
)
name: str = Field(..., description="Task name.", examples=["Buy groceries"])
completed: bool = Field(
default=False,
description="Indicates whether the task is completed; defaults to false.",
)


class UpdateTaskModel(BaseModel):
model_config = ConfigDict(
json_schema_extra={
"example": {
"name": "My important task",
"name": "Buy groceries",
"completed": True,
}
}
)

name: Optional[str] = None
completed: Optional[bool] = None
name: Optional[str] = Field(
default=None,
description="New name; if omitted or null, it remains unchanged.",
examples=["Buy groceries"],
)
completed: Optional[bool] = Field(
default=None,
description="New completion status; if omitted or null, it remains unchanged.",
)
205 changes: 194 additions & 11 deletions backend/apps/todo/routers.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,124 @@
from fastapi import APIRouter, Body, Request, HTTPException, status
from typing import Annotated

from fastapi import APIRouter, Body, Path, Request, HTTPException, status
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder

from .models import TaskModel, UpdateTaskModel

router = APIRouter()


@router.post("/", response_description="Add new task")
async def create_task(request: Request, task: TaskModel = Body(...)):
TASK_EXAMPLE = {
"_id": "9e46475a-2ea8-4fdc-a97f-bfd57e9df932",
"name": "Buy groceries",
"completed": False,
}
TASK_SCHEMA = {
"type": "object",
"required": ["_id", "name", "completed"],
"properties": {
"_id": {"type": "string", "description": "Task identifier."},
"name": {"type": "string", "description": "Task name."},
"completed": {"type": "boolean", "description": "Completion status."},
},
}
TASK_RESPONSE = {
"description": "Task returned, including its identifier.",
"content": {"application/json": {"schema": TASK_SCHEMA, "example": TASK_EXAMPLE}},
}
NOT_FOUND_RESPONSE = {
"description": "No task was found with the provided identifier.",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": ["detail"],
"properties": {"detail": {"type": "string"}},
},
"example": {"detail": "Task nonexistent-id not found"},
}
},
}


def validation_response(example):
return {
"description": "Invalid body or missing required field.",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"detail": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {"type": "string"},
"loc": {"type": "array", "items": {}},
"msg": {"type": "string"},
"input": {},
},
},
}
},
},
"example": {"detail": [example]},
}
},
}


TaskId = Annotated[
str,
Path(
description=(
"Task string identifier, corresponding to the _id field. "
"The UUID format is not validated."
),
examples=["9e46475a-2ea8-4fdc-a97f-bfd57e9df932"],
),
]


@router.post(
"/",
status_code=status.HTTP_201_CREATED,
summary="Create a task",
description=(
"Creates a task with a required `name`. `completed` is optional and defaults "
"to `false`. `_id` is optional: if omitted, a UUID v4 is generated; you can "
"also send your own string in `_id` or `id`, without UUID format validation. "
"A duplicate identifier may cause a server error."
),
responses={
201: TASK_RESPONSE,
422: validation_response(
{
"type": "missing",
"loc": ["body", "name"],
"msg": "Field required",
"input": {},
}
),
500: {
"description": "Server error, for example, when using a duplicate identifier."
},
},
)
async def create_task(
request: Request,
task: TaskModel = Body(
...,
openapi_examples={
"generate_id": {
"summary": "Generate identifier automatically",
"value": {"name": "Buy groceries"},
},
"provide_id": {"summary": "Provide identifier", "value": TASK_EXAMPLE},
},
),
):
task = jsonable_encoder(task)
new_task = await request.app.mongodb["tasks"].insert_one(task)
created_task = await request.app.mongodb["tasks"].find_one(
Expand All @@ -18,24 +128,80 @@ async def create_task(request: Request, task: TaskModel = Body(...)):
return JSONResponse(status_code=status.HTTP_201_CREATED, content=created_task)


@router.get("/", response_description="List all tasks")
@router.get(
"/",
summary="List tasks",
description=(
"Returns up to 100 tasks, with no guaranteed order and no pagination. "
"If there are no tasks, returns an empty list."
),
responses={
200: {
"description": "List of tasks, which may be empty.",
"content": {
"application/json": {
"schema": {"type": "array", "items": TASK_SCHEMA},
"examples": {
"tasks": {"summary": "One task", "value": [TASK_EXAMPLE]},
"empty": {"summary": "No tasks", "value": []},
},
}
},
}
},
)
async def list_tasks(request: Request):
tasks = []
for doc in await request.app.mongodb["tasks"].find().to_list(length=100):
tasks.append(doc)
return tasks


@router.get("/{id}", response_description="Get a single task")
async def show_task(id: str, request: Request):
@router.get(
"/{id}",
summary="Get a task",
description="Retrieves a task by the exact identifier provided in the path.",
responses={200: TASK_RESPONSE, 404: NOT_FOUND_RESPONSE},
)
async def show_task(id: TaskId, request: Request):
if (task := await request.app.mongodb["tasks"].find_one({"_id": id})) is not None:
return task

raise HTTPException(status_code=404, detail=f"Task {id} not found")


@router.put("/{id}", response_description="Update a task")
async def update_task(id: str, request: Request, task: UpdateTaskModel = Body(...)):
@router.put(
"/{id}",
summary="Update a task",
description=(
"Partially updates `name` and/or `completed`. Omitted fields or fields with "
"a `null` value are ignored. An empty object or an update with no changes "
"returns the existing task; the identifier cannot be changed through this route."
),
responses={
200: TASK_RESPONSE,
404: NOT_FOUND_RESPONSE,
422: validation_response(
{
"type": "bool_parsing",
"loc": ["body", "completed"],
"msg": "Input should be a valid boolean, unable to interpret input",
"input": "invalid",
}
),
},
)
async def update_task(
id: TaskId,
request: Request,
task: UpdateTaskModel = Body(
...,
openapi_examples={
"complete": {"summary": "Complete task", "value": {"completed": True}},
"no_changes": {"summary": "Keep task unchanged", "value": {}},
},
),
):
task = {k: v for k, v in task.dict().items() if v is not None}

if len(task) >= 1:
Expand All @@ -57,8 +223,25 @@ async def update_task(id: str, request: Request, task: UpdateTaskModel = Body(..
raise HTTPException(status_code=404, detail=f"Task {id} not found")


@router.delete("/{id}", response_description="Delete Task")
async def delete_task(id: str, request: Request):
@router.delete(
"/{id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Delete a task",
description=(
"Permanently deletes the identified task. The intended response is 204, "
"with no body. **Known issue:** currently, after deleting an existing task, "
"building the response fails and may result in a 500. In that case the task "
"has already been deleted; check before trying again."
),
responses={
204: {
"description": "Intended response for a successful deletion, with no body."
},
404: NOT_FOUND_RESPONSE,
500: {"description": "Known error after deleting an existing task."},
},
)
async def delete_task(id: TaskId, request: Request):
delete_result = await request.app.mongodb["tasks"].delete_one({"_id": id})

if delete_result.deleted_count == 1:
Expand Down
11 changes: 10 additions & 1 deletion backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,16 @@ async def lifespan(app: FastAPI):
app.mongodb_client.close()


app = FastAPI(lifespan=lifespan)
app = FastAPI(
title="FARM Intro Task API",
description=(
"API for creating, retrieving, updating, and deleting tasks. "
"Interactive documentation is available at /docs and the OpenAPI schema at /openapi.json."
),
version="1.0.0",
openapi_tags=[{"name": "tasks", "description": "Task management operations."}],
lifespan=lifespan,
)

app.include_router(todo_router, tags=["tasks"], prefix="/task")

Expand Down
Loading