From f48308f6eaaec75d0ffda654dfbf93c8f4571f70 Mon Sep 17 00:00:00 2001 From: "rodrigo.cabral" Date: Mon, 30 Nov 2026 11:26:12 -0300 Subject: [PATCH 1/2] Enhance API documentation and testing framework - Update FastAPI app initialization with title, description, and version. - Add OpenAPI schema and HTTP behavior tests without MongoDB dependency. - Modify task models to include detailed descriptions and examples. - Improve task router with enhanced response descriptions and validation. - Update CI workflow to include API documentation tests. --- .github/workflows/ci.yml | 5 +- README.md | 14 ++- backend/apps/todo/models.py | 38 +++++-- backend/apps/todo/routers.py | 205 +++++++++++++++++++++++++++++++++-- backend/main.py | 13 ++- tests/test_api_docs.py | 162 +++++++++++++++++++++++++++ 6 files changed, 413 insertions(+), 24 deletions(-) create mode 100644 tests/test_api_docs.py 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..7c75811 100644 --- a/backend/apps/todo/models.py +++ b/backend/apps/todo/models.py @@ -9,27 +9,47 @@ 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": "Comprar alimentos", + "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=( + "Identificador da tarefa. Quando omitido, um UUID v4 é gerado. " + "Também aceita uma string informada pelo cliente, sem validar o formato UUID." + ), + examples=["9e46475a-2ea8-4fdc-a97f-bfd57e9df932"], + ) + name: str = Field( + ..., description="Nome da tarefa.", examples=["Comprar alimentos"] + ) + completed: bool = Field( + default=False, + description="Indica se a tarefa foi concluída; por padrão, é false.", + ) class UpdateTaskModel(BaseModel): model_config = ConfigDict( json_schema_extra={ "example": { - "name": "My important task", + "name": "Comprar alimentos", "completed": True, } } ) - name: Optional[str] = None - completed: Optional[bool] = None + name: Optional[str] = Field( + default=None, + description="Novo nome; se omitido ou null, permanece inalterado.", + examples=["Comprar alimentos"], + ) + completed: Optional[bool] = Field( + default=None, + description="Novo estado de conclusão; se omitido ou null, permanece inalterado.", + ) diff --git a/backend/apps/todo/routers.py b/backend/apps/todo/routers.py index 5212f9d..133ebd1 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": "Comprar alimentos", + "completed": False, +} +TASK_SCHEMA = { + "type": "object", + "required": ["_id", "name", "completed"], + "properties": { + "_id": {"type": "string", "description": "Identificador da tarefa."}, + "name": {"type": "string", "description": "Nome da tarefa."}, + "completed": {"type": "boolean", "description": "Estado de conclusão."}, + }, +} +TASK_RESPONSE = { + "description": "Tarefa retornada, incluindo seu identificador.", + "content": {"application/json": {"schema": TASK_SCHEMA, "example": TASK_EXAMPLE}}, +} +NOT_FOUND_RESPONSE = { + "description": "Nenhuma tarefa foi encontrada com o identificador informado.", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": ["detail"], + "properties": {"detail": {"type": "string"}}, + }, + "example": {"detail": "Task id-inexistente not found"}, + } + }, +} + + +def validation_response(example): + return { + "description": "Corpo inválido ou campo obrigatório ausente.", + "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=( + "Identificador string da tarefa, correspondente ao campo _id. " + "O formato UUID não é validado." + ), + examples=["9e46475a-2ea8-4fdc-a97f-bfd57e9df932"], + ), +] + + +@router.post( + "/", + status_code=status.HTTP_201_CREATED, + summary="Criar uma tarefa", + description=( + "Cria uma tarefa com `name` obrigatório. `completed` é opcional e assume " + "`false`. `_id` é opcional: se omitido, um UUID v4 é gerado; também é " + "possível enviar uma string própria em `_id` ou `id`, sem validação do " + "formato UUID. Um identificador duplicado pode causar erro do servidor." + ), + responses={ + 201: TASK_RESPONSE, + 422: validation_response( + { + "type": "missing", + "loc": ["body", "name"], + "msg": "Field required", + "input": {}, + } + ), + 500: { + "description": "Erro do servidor, por exemplo, ao usar um identificador duplicado." + }, + }, +) +async def create_task( + request: Request, + task: TaskModel = Body( + ..., + openapi_examples={ + "gerar_id": { + "summary": "Gerar identificador automaticamente", + "value": {"name": "Comprar alimentos"}, + }, + "informar_id": {"summary": "Informar identificador", "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="Listar tarefas", + description=( + "Retorna até 100 tarefas, sem ordem garantida e sem paginação. " + "Se não houver tarefas, retorna uma lista vazia." + ), + responses={ + 200: { + "description": "Lista de tarefas, que pode estar vazia.", + "content": { + "application/json": { + "schema": {"type": "array", "items": TASK_SCHEMA}, + "examples": { + "tarefas": {"summary": "Uma tarefa", "value": [TASK_EXAMPLE]}, + "vazia": {"summary": "Nenhuma tarefa", "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="Consultar uma tarefa", + description="Busca uma tarefa pelo identificador exato informado no caminho.", + 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="Atualizar uma tarefa", + description=( + "Atualiza parcialmente `name` e/ou `completed`. Campos omitidos ou com " + "valor `null` são ignorados. Um objeto vazio ou sem alterações retorna " + "a tarefa existente; não é possível alterar o identificador por esta rota." + ), + 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={ + "concluir": {"summary": "Concluir tarefa", "value": {"completed": True}}, + "sem_alteracoes": {"summary": "Manter tarefa inalterada", "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="Excluir uma tarefa", + description=( + "Exclui permanentemente a tarefa identificada. A resposta pretendida é " + "204, sem corpo. **Problema conhecido:** atualmente, após excluir uma " + "tarefa existente, a construção da resposta falha e pode resultar em 500. " + "Nesse caso a tarefa já foi excluída; consultar antes de tentar novamente." + ), + responses={ + 204: { + "description": "Resposta pretendida para exclusão bem-sucedida, sem corpo." + }, + 404: NOT_FOUND_RESPONSE, + 500: {"description": "Erro conhecido após a exclusão de uma tarefa existente."}, + }, +) +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..c942d37 100644 --- a/backend/main.py +++ b/backend/main.py @@ -19,7 +19,18 @@ async def lifespan(app: FastAPI): app.mongodb_client.close() -app = FastAPI(lifespan=lifespan) +app = FastAPI( + title="API de tarefas FARM Intro", + description=( + "API para criar, consultar, atualizar e excluir tarefas. " + "A documentação interativa está em /docs e o esquema OpenAPI em /openapi.json." + ), + version="1.0.0", + openapi_tags=[ + {"name": "tasks", "description": "Operações de gerenciamento de tarefas."} + ], + 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..7a43c24 --- /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"] == "API de tarefas FARM Intro" + 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 id-inexistente not found" + + create = paths["/task/"]["post"] + assert "200" not in create["responses"] + assert create["requestBody"]["content"]["application/json"]["examples"]["gerar_id"][ + "value" + ] == {"name": "Comprar alimentos"} + 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"]["vazia"]["value"] == [] + deletion = paths["/task/{id}"]["delete"] + assert "content" not in deletion["responses"]["204"] + assert "Problema conhecido" 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 From 711f886001ca1b3dcb59972ad1d77ef25f9f23de Mon Sep 17 00:00:00 2001 From: "rodrigo.cabral" Date: Thu, 3 Dec 2026 11:37:44 -0300 Subject: [PATCH 2/2] docs: translate OpenAPI documentation to English Translate Swagger/OpenAPI summaries, descriptions, response examples, and model field documentation from Portuguese to English. Update API docs tests to match the translated contract. --- backend/apps/todo/models.py | 20 ++++----- backend/apps/todo/routers.py | 82 ++++++++++++++++++------------------ backend/main.py | 10 ++--- tests/test_api_docs.py | 14 +++--- 4 files changed, 61 insertions(+), 65 deletions(-) diff --git a/backend/apps/todo/models.py b/backend/apps/todo/models.py index 7c75811..d3bcd8a 100644 --- a/backend/apps/todo/models.py +++ b/backend/apps/todo/models.py @@ -10,7 +10,7 @@ class TaskModel(BaseModel): json_schema_extra={ "example": { "_id": "9e46475a-2ea8-4fdc-a97f-bfd57e9df932", - "name": "Comprar alimentos", + "name": "Buy groceries", "completed": False, } }, @@ -20,17 +20,15 @@ class TaskModel(BaseModel): default_factory=lambda: str(uuid.uuid4()), alias="_id", description=( - "Identificador da tarefa. Quando omitido, um UUID v4 é gerado. " - "Também aceita uma string informada pelo cliente, sem validar o formato UUID." + "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="Nome da tarefa.", examples=["Comprar alimentos"] - ) + name: str = Field(..., description="Task name.", examples=["Buy groceries"]) completed: bool = Field( default=False, - description="Indica se a tarefa foi concluída; por padrão, é false.", + description="Indicates whether the task is completed; defaults to false.", ) @@ -38,7 +36,7 @@ class UpdateTaskModel(BaseModel): model_config = ConfigDict( json_schema_extra={ "example": { - "name": "Comprar alimentos", + "name": "Buy groceries", "completed": True, } } @@ -46,10 +44,10 @@ class UpdateTaskModel(BaseModel): name: Optional[str] = Field( default=None, - description="Novo nome; se omitido ou null, permanece inalterado.", - examples=["Comprar alimentos"], + description="New name; if omitted or null, it remains unchanged.", + examples=["Buy groceries"], ) completed: Optional[bool] = Field( default=None, - description="Novo estado de conclusão; se omitido ou null, permanece inalterado.", + 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 133ebd1..9ca5e8b 100644 --- a/backend/apps/todo/routers.py +++ b/backend/apps/todo/routers.py @@ -10,24 +10,24 @@ TASK_EXAMPLE = { "_id": "9e46475a-2ea8-4fdc-a97f-bfd57e9df932", - "name": "Comprar alimentos", + "name": "Buy groceries", "completed": False, } TASK_SCHEMA = { "type": "object", "required": ["_id", "name", "completed"], "properties": { - "_id": {"type": "string", "description": "Identificador da tarefa."}, - "name": {"type": "string", "description": "Nome da tarefa."}, - "completed": {"type": "boolean", "description": "Estado de conclusão."}, + "_id": {"type": "string", "description": "Task identifier."}, + "name": {"type": "string", "description": "Task name."}, + "completed": {"type": "boolean", "description": "Completion status."}, }, } TASK_RESPONSE = { - "description": "Tarefa retornada, incluindo seu identificador.", + "description": "Task returned, including its identifier.", "content": {"application/json": {"schema": TASK_SCHEMA, "example": TASK_EXAMPLE}}, } NOT_FOUND_RESPONSE = { - "description": "Nenhuma tarefa foi encontrada com o identificador informado.", + "description": "No task was found with the provided identifier.", "content": { "application/json": { "schema": { @@ -35,7 +35,7 @@ "required": ["detail"], "properties": {"detail": {"type": "string"}}, }, - "example": {"detail": "Task id-inexistente not found"}, + "example": {"detail": "Task nonexistent-id not found"}, } }, } @@ -43,7 +43,7 @@ def validation_response(example): return { - "description": "Corpo inválido ou campo obrigatório ausente.", + "description": "Invalid body or missing required field.", "content": { "application/json": { "schema": { @@ -73,8 +73,8 @@ def validation_response(example): str, Path( description=( - "Identificador string da tarefa, correspondente ao campo _id. " - "O formato UUID não é validado." + "Task string identifier, corresponding to the _id field. " + "The UUID format is not validated." ), examples=["9e46475a-2ea8-4fdc-a97f-bfd57e9df932"], ), @@ -84,12 +84,12 @@ def validation_response(example): @router.post( "/", status_code=status.HTTP_201_CREATED, - summary="Criar uma tarefa", + summary="Create a task", description=( - "Cria uma tarefa com `name` obrigatório. `completed` é opcional e assume " - "`false`. `_id` é opcional: se omitido, um UUID v4 é gerado; também é " - "possível enviar uma string própria em `_id` ou `id`, sem validação do " - "formato UUID. Um identificador duplicado pode causar erro do servidor." + "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, @@ -102,7 +102,7 @@ def validation_response(example): } ), 500: { - "description": "Erro do servidor, por exemplo, ao usar um identificador duplicado." + "description": "Server error, for example, when using a duplicate identifier." }, }, ) @@ -111,11 +111,11 @@ async def create_task( task: TaskModel = Body( ..., openapi_examples={ - "gerar_id": { - "summary": "Gerar identificador automaticamente", - "value": {"name": "Comprar alimentos"}, + "generate_id": { + "summary": "Generate identifier automatically", + "value": {"name": "Buy groceries"}, }, - "informar_id": {"summary": "Informar identificador", "value": TASK_EXAMPLE}, + "provide_id": {"summary": "Provide identifier", "value": TASK_EXAMPLE}, }, ), ): @@ -130,20 +130,20 @@ async def create_task( @router.get( "/", - summary="Listar tarefas", + summary="List tasks", description=( - "Retorna até 100 tarefas, sem ordem garantida e sem paginação. " - "Se não houver tarefas, retorna uma lista vazia." + "Returns up to 100 tasks, with no guaranteed order and no pagination. " + "If there are no tasks, returns an empty list." ), responses={ 200: { - "description": "Lista de tarefas, que pode estar vazia.", + "description": "List of tasks, which may be empty.", "content": { "application/json": { "schema": {"type": "array", "items": TASK_SCHEMA}, "examples": { - "tarefas": {"summary": "Uma tarefa", "value": [TASK_EXAMPLE]}, - "vazia": {"summary": "Nenhuma tarefa", "value": []}, + "tasks": {"summary": "One task", "value": [TASK_EXAMPLE]}, + "empty": {"summary": "No tasks", "value": []}, }, } }, @@ -159,8 +159,8 @@ async def list_tasks(request: Request): @router.get( "/{id}", - summary="Consultar uma tarefa", - description="Busca uma tarefa pelo identificador exato informado no caminho.", + 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): @@ -172,11 +172,11 @@ async def show_task(id: TaskId, request: Request): @router.put( "/{id}", - summary="Atualizar uma tarefa", + summary="Update a task", description=( - "Atualiza parcialmente `name` e/ou `completed`. Campos omitidos ou com " - "valor `null` são ignorados. Um objeto vazio ou sem alterações retorna " - "a tarefa existente; não é possível alterar o identificador por esta rota." + "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, @@ -197,8 +197,8 @@ async def update_task( task: UpdateTaskModel = Body( ..., openapi_examples={ - "concluir": {"summary": "Concluir tarefa", "value": {"completed": True}}, - "sem_alteracoes": {"summary": "Manter tarefa inalterada", "value": {}}, + "complete": {"summary": "Complete task", "value": {"completed": True}}, + "no_changes": {"summary": "Keep task unchanged", "value": {}}, }, ), ): @@ -226,19 +226,19 @@ async def update_task( @router.delete( "/{id}", status_code=status.HTTP_204_NO_CONTENT, - summary="Excluir uma tarefa", + summary="Delete a task", description=( - "Exclui permanentemente a tarefa identificada. A resposta pretendida é " - "204, sem corpo. **Problema conhecido:** atualmente, após excluir uma " - "tarefa existente, a construção da resposta falha e pode resultar em 500. " - "Nesse caso a tarefa já foi excluída; consultar antes de tentar novamente." + "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": "Resposta pretendida para exclusão bem-sucedida, sem corpo." + "description": "Intended response for a successful deletion, with no body." }, 404: NOT_FOUND_RESPONSE, - 500: {"description": "Erro conhecido após a exclusão de uma tarefa existente."}, + 500: {"description": "Known error after deleting an existing task."}, }, ) async def delete_task(id: TaskId, request: Request): diff --git a/backend/main.py b/backend/main.py index c942d37..cd5bc6e 100644 --- a/backend/main.py +++ b/backend/main.py @@ -20,15 +20,13 @@ async def lifespan(app: FastAPI): app = FastAPI( - title="API de tarefas FARM Intro", + title="FARM Intro Task API", description=( - "API para criar, consultar, atualizar e excluir tarefas. " - "A documentação interativa está em /docs e o esquema OpenAPI em /openapi.json." + "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": "Operações de gerenciamento de tarefas."} - ], + openapi_tags=[{"name": "tasks", "description": "Task management operations."}], lifespan=lifespan, ) diff --git a/tests/test_api_docs.py b/tests/test_api_docs.py index 7a43c24..44014d4 100644 --- a/tests/test_api_docs.py +++ b/tests/test_api_docs.py @@ -65,7 +65,7 @@ def test_openapi_documents_every_endpoint(api): response = client.get("/openapi.json") assert response.status_code == 200 schema = response.json() - assert schema["info"]["title"] == "API de tarefas FARM Intro" + assert schema["info"]["title"] == "FARM Intro Task API" assert schema["info"]["version"] == "1.0.0" assert client.get("/docs").status_code == 200 @@ -88,22 +88,22 @@ def test_openapi_documents_every_endpoint(api): example = operation["responses"]["404"]["content"]["application/json"][ "example" ] - assert example["detail"] == "Task id-inexistente not found" + 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"]["gerar_id"][ - "value" - ] == {"name": "Comprar alimentos"} + 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"]["vazia"]["value"] == [] + assert listing["examples"]["empty"]["value"] == [] deletion = paths["/task/{id}"]["delete"] assert "content" not in deletion["responses"]["204"] - assert "Problema conhecido" in deletion["description"] + assert "Known issue" in deletion["description"] models = schema["components"]["schemas"] task = models["TaskModel"]