diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e58c5f4..ad97ad4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: diff --git a/README.md b/README.md index 73e72cd..dc14677 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 ``` @@ -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 | - diff --git a/backend/apps/todo/models.py b/backend/apps/todo/models.py index 4578f16..d3bcd8a 100644 --- a/backend/apps/todo/models.py +++ b/backend/apps/todo/models.py @@ -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.", + ) diff --git a/backend/apps/todo/routers.py b/backend/apps/todo/routers.py index 5212f9d..9ca5e8b 100644 --- a/backend/apps/todo/routers.py +++ b/backend/apps/todo/routers.py @@ -1,4 +1,6 @@ -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 @@ -6,9 +8,117 @@ 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( @@ -18,7 +128,28 @@ 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): @@ -26,16 +157,51 @@ async def list_tasks(request: Request): 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: @@ -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: diff --git a/backend/main.py b/backend/main.py index 7be45f6..cd5bc6e 100644 --- a/backend/main.py +++ b/backend/main.py @@ -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") diff --git a/tests/test_api_docs.py b/tests/test_api_docs.py new file mode 100644 index 0000000..44014d4 --- /dev/null +++ b/tests/test_api_docs.py @@ -0,0 +1,162 @@ +"""Check the OpenAPI contract and HTTP behavior without a MongoDB server.""" + +from pathlib import Path +from types import SimpleNamespace +from uuid import UUID + +import pytest +from fastapi.testclient import TestClient + + +class FakeTasks: + def __init__(self): + self.documents = {} + + async def insert_one(self, document): + self.documents[document["_id"]] = document.copy() + return SimpleNamespace(inserted_id=document["_id"]) + + async def find_one(self, query): + document = self.documents.get(query["_id"]) + return document.copy() if document is not None else None + + def find(self): + tasks = self + + class Cursor: + async def to_list(self, length): + return [doc.copy() for doc in list(tasks.documents.values())[:length]] + + return Cursor() + + async def update_one(self, query, update): + document = self.documents.get(query["_id"]) + if document is None: + return SimpleNamespace(modified_count=0) + changed = any( + document.get(key) != value for key, value in update["$set"].items() + ) + document.update(update["$set"]) + return SimpleNamespace(modified_count=int(changed)) + + async def delete_one(self, query): + return SimpleNamespace( + deleted_count=int(self.documents.pop(query["_id"], None) is not None) + ) + + +@pytest.fixture +def api(monkeypatch): + monkeypatch.setenv("DB_URL", "mongodb://localhost:27017/") + monkeypatch.setenv("DB_NAME", "test") + monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "backend")) + from main import app + + tasks = FakeTasks() + monkeypatch.setattr(app, "mongodb", {"tasks": tasks}, raising=False) + # Without the context manager TestClient does not run the MongoDB lifespan. + client = TestClient(app, raise_server_exceptions=False) + yield client, tasks + client.close() + + +def test_openapi_documents_every_endpoint(api): + client, _ = api + response = client.get("/openapi.json") + assert response.status_code == 200 + schema = response.json() + assert schema["info"]["title"] == "FARM Intro Task API" + assert schema["info"]["version"] == "1.0.0" + assert client.get("/docs").status_code == 200 + + paths = schema["paths"] + expected = { + ("/task/", "post"): {"201", "422", "500"}, + ("/task/", "get"): {"200"}, + ("/task/{id}", "get"): {"200", "404"}, + ("/task/{id}", "put"): {"200", "404", "422"}, + ("/task/{id}", "delete"): {"204", "404", "500"}, + } + for (path, method), statuses in expected.items(): + operation = paths[path][method] + assert operation["summary"] and operation["description"] + assert statuses <= operation["responses"].keys() + if "{id}" in path: + parameter = operation["parameters"][0] + assert parameter["name"] == "id" and parameter["description"] + if "404" in statuses: + example = operation["responses"]["404"]["content"]["application/json"][ + "example" + ] + assert example["detail"] == "Task nonexistent-id not found" + + create = paths["/task/"]["post"] + assert "200" not in create["responses"] + assert create["requestBody"]["content"]["application/json"]["examples"][ + "generate_id" + ]["value"] == {"name": "Buy groceries"} + task_response = create["responses"]["201"]["content"]["application/json"] + assert set(task_response["schema"]["required"]) == {"_id", "name", "completed"} + assert "_id" in task_response["example"] + listing = paths["/task/"]["get"]["responses"]["200"]["content"]["application/json"] + assert listing["schema"]["type"] == "array" + assert listing["examples"]["empty"]["value"] == [] + deletion = paths["/task/{id}"]["delete"] + assert "content" not in deletion["responses"]["204"] + assert "Known issue" in deletion["description"] + + models = schema["components"]["schemas"] + task = models["TaskModel"] + assert task["required"] == ["name"] + assert task["properties"]["completed"]["default"] is False + assert task["properties"]["_id"]["description"] + assert "_id" in task["example"] + assert "required" not in models["UpdateTaskModel"] + + +def test_create_list_and_update_match_documentation(api): + client, tasks = api + assert client.get("/task/").json() == [] + created = client.post("/task/", json={"name": "Comprar alimentos"}) + assert created.status_code == 201 + task = created.json() + assert UUID(task["_id"]).version == 4 + assert task["name"] == "Comprar alimentos" and task["completed"] is False + assert client.get(f"/task/{task['_id']}").json() == task + assert client.get("/task/").json() == [task] + + updated = client.put(f"/task/{task['_id']}", json={"completed": True, "name": None}) + assert updated.status_code == 200 + assert updated.json() == {**task, "completed": True} + assert client.put(f"/task/{task['_id']}", json={}).json() == updated.json() + assert ( + client.post("/task/", json={"_id": "custom-id", "name": "Outra"}).status_code + == 201 + ) + assert client.get("/task/custom-id").json()["_id"] == "custom-id" + for i in range(101): + tasks.documents[str(i)] = {"_id": str(i), "name": "Teste", "completed": False} + assert len(client.get("/task/").json()) == 100 + + +def test_errors_and_known_delete_issue(api): + client, _ = api + openapi = client.get("/openapi.json").json() + create_error = client.post("/task/", json={}) + assert create_error.status_code == 422 + documented = openapi["paths"]["/task/"]["post"]["responses"]["422"] + assert create_error.json() == documented["content"]["application/json"]["example"] + update_error = client.put("/task/missing", json={"completed": "invalid"}) + assert update_error.status_code == 422 + documented = openapi["paths"]["/task/{id}"]["put"]["responses"]["422"] + assert update_error.json() == documented["content"]["application/json"]["example"] + for method in (client.get, client.delete): + response = method("/task/missing") + assert response.status_code == 404 + assert response.json() == {"detail": "Task missing not found"} + assert client.put("/task/missing", json={}).status_code == 404 + + client.post("/task/", json={"_id": "to-delete", "name": "Excluir"}) + # Current behavior: deletion succeeds, but JSONResponse is constructed incorrectly. + assert client.delete("/task/to-delete").status_code == 500 + assert client.get("/task/to-delete").status_code == 404