Skip to content

feat(api): add Entity CRUD REST endpoints with auth and pagination [AYG-70]#2211

Closed
amostt wants to merge 9 commits intofastapi:masterfrom
Aygentic:amos/ayg-70-entity-api-endpoints-r2
Closed

feat(api): add Entity CRUD REST endpoints with auth and pagination [AYG-70]#2211
amostt wants to merge 9 commits intofastapi:masterfrom
Aygentic:amos/ayg-70-entity-api-endpoints-r2

Conversation

@amostt
Copy link

@amostt amostt commented Feb 28, 2026

Summary

  • Add 5 thin CRUD route handlers (POST/GET/GET/{id}/PATCH/{id}/DELETE/{id}) at /api/v1/entities
  • All endpoints require Clerk JWT authentication (PrincipalDep) and delegate to entity_service
  • Pagination validated at route layer: offset>=0, limit 1-100 via Query constraints
  • 22 integration tests covering full CRUD lifecycle, auth enforcement, ownership isolation, validation, and pagination

Changes

  • CREATE backend/app/api/routes/entities.py — 5 route handlers
  • MODIFY backend/app/api/main.py — register entities router
  • CREATE backend/tests/integration/test_entities.py — 22 integration tests

Acceptance Criteria

  • AC-1: POST /api/v1/entities creates entity with 201, owner_id from JWT
  • AC-2: GET /api/v1/entities returns paginated list (data + count) with offset/limit defaults
  • AC-3: GET /api/v1/entities/{id} returns entity for valid owned ID
  • AC-4: PATCH /api/v1/entities/{id} updates only provided fields
  • AC-5: DELETE /api/v1/entities/{id} returns 204
  • AC-6: No auth → 401 on all entity endpoints
  • AC-7: Non-owned entity → 404 (not 403)
  • AC-8: Invalid POST body → 422 with details array
  • AC-9: Pagination limit capped at 100 (422 rejection at route layer)
  • AC-10: Non-existent UUID → 404 with ENTITY_NOT_FOUND code

Review Summary

  • Critical: 0 | High: 0 (2 high findings auto-fixed) | Medium: 5 | Low: 8
  • 3-subagent parallel review (code-quality, test-coverage, security)
  • Auto-fixed: pagination Query constraints (FUNC-001/SEC-001), error code assertions (TEST-001)
  • All 188 backend tests passing, lint/types clean
  • Security: No critical issues. Auth, IDOR prevention, injection protection all verified.

Test Plan

  • 22 integration tests passing (uv run pytest backend/tests/integration/test_entities.py -v)
  • 188 total backend tests passing (zero regressions)
  • Ruff lint clean
  • mypy typecheck clean
  • Manual: curl -H "Authorization: Bearer <token>" http://localhost:8000/api/v1/entities

Fixes AYG-70
Related to AYG-64

🤖 Generated with Claude Code by Aygentic

amostt and others added 9 commits February 27, 2026 03:54
Rename default branch from master to main across all CI workflows,
documentation, and PRD. Also adds comprehensive project documentation
generated by the initialise skill (CLAUDE.md, docs/ structure).

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>
#1)

* feat(core): rewrite config, error handlers, and shared models [AYG-65]

- Replace PostgreSQL/SMTP settings with Supabase+Clerk env vars
- Add frozen Settings with production secret and CORS guards
- Create unified error response shape with global exception handlers
- Add shared Pydantic models: ErrorResponse, ValidationErrorResponse, PaginatedResponse, Principal

Fixes AYG-65

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

* fix(core): untrack .env and guard conftest for migration [AYG-65]

- Remove .env from git tracking and add to .gitignore (SEC-001)
- Guard integration test conftest.py imports with try/except so unit
  tests run without --noconftest during the migration (FUNC-002)

Related to AYG-65

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

* fix(tests): harden test isolation for template usage [AYG-65]

- Catch all exceptions (including ValidationError) in conftest guard so
  pytest doesn't crash when env vars are unset in a fresh template clone
- Explicitly delenv missing vars in test_missing_required_var_raises so
  the test is deterministic regardless of the caller's shell environment

Related to AYG-65

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

* docs(project): update documentation before merge [skip ci]

Updated documentation based on AYG-65 code changes:
- setup.md: replaced PostgreSQL/SMTP/JWT env vars with Supabase/Clerk
- deployment/environments.md: updated all env tables and GitHub Secrets
- architecture/overview.md: added error handling framework, shared models, Clerk auth
- architecture/decisions/: new ADRs for error handling and models package
- api/overview.md: Clerk auth, standard error shape, paginated response pattern
- api/endpoints/login.md: deprecated (Clerk migration)
- api/endpoints/users.md + items.md: updated auth and error response docs
- data/models.md: new Shared Pydantic Models section
- testing/test-registry.md: +36 unit tests, closed config coverage gap

Related to AYG-65

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

---------

Co-authored-by: Aygentic <noreply@aygentic.com>
…YG-66] (#2)

* feat(core): add structured logging and request pipeline middleware [AYG-66]

Add structlog-based structured logging (JSON/console modes) and request
pipeline middleware providing UUID v4 request IDs, correlation ID
propagation, security headers on all responses (including CORS preflight),
and status-based log levels (info/warning/error for 2xx/4xx/5xx).

- Create backend/app/core/logging.py: structlog configuration with
  JSON renderer (production) and ConsoleRenderer (local dev), base
  fields (timestamp, level, event, service, version, environment),
  contextvars integration for request-scoped fields
- Create backend/app/core/middleware.py: RequestPipelineMiddleware
  with request_id generation, X-Correlation-ID propagation, 6 security
  headers (X-Content-Type-Options, X-Frame-Options, X-XSS-Protection,
  Referrer-Policy, Permissions-Policy, HSTS production-only),
  X-Request-ID on every response including error and exception paths
- Wire into main.py with documented middleware ordering (outermost
  wraps CORSMiddleware so preflight OPTIONS get headers too)
- 32 new unit tests (6 logging + 26 middleware) covering CORS preflight
  header behavior, X-Request-ID on 4xx/5xx/exception paths, and
  negative tests proving Authorization/Cookie values never logged

Fixes AYG-66

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

* docs(core): update architecture, test registry, and deployment docs for AYG-66 [skip ci]

Updated documentation based on structured logging and request pipeline middleware implementation.

Related to AYG-66

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

---------

Co-authored-by: Aygentic <noreply@aygentic.com>
…ed deps [AYG-67] (#3)

Implement the three core infrastructure dependencies for the microservice template:

- Supabase client: factory function + FastAPI dependency from app.state
- Clerk JWT auth: validate Bearer tokens, extract Principal with roles,
  map error reasons to structured error codes (AUTH_MISSING_TOKEN,
  AUTH_EXPIRED_TOKEN, AUTH_INVALID_TOKEN)
- HTTP client wrapper: async httpx with retry on 502/503/504,
  exponential backoff, circuit breaker (5 failures/60s window),
  X-Request-ID/X-Correlation-ID header propagation from structlog
- Typed FastAPI dependencies: SupabaseDep, PrincipalDep, HttpClientDep,
  RequestIdDep via Annotated[T, Depends()]
- Lifespan context manager: init Supabase + HttpClient at startup,
  close httpx pool on shutdown
- Added session_id field to Principal model

44 new unit tests (113 total), all passing.

Fixes AYG-67

🤖 Generated by Aygentic

Co-authored-by: Aygentic <noreply@aygentic.com>
#4)

* feat(api): add operational endpoints health/readiness/version [AYG-68]

- Add /healthz, /readyz, /version root endpoints
- Add readiness Supabase check with resilient 503 response path
- Add integration tests for schemas, auth-free access, and failure paths

Fixes AYG-68

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

* fix(api): address code review findings for health endpoints [AYG-68]

- Offload sync Supabase check to thread pool via anyio.to_thread.run_sync
  to avoid blocking the async event loop (BUG-001)
- Use select("*", head=True) for lighter HEAD connectivity probe (QUAL-001)
- Add explicit AttributeError catch for missing Supabase client (QUAL-002)
- Replace str(exc) with error_type= in logger to prevent credential leak (SEC-001)
- Patch settings in test_includes_service_name and test_default_values_for_unset_env_vars
  for CI robustness (TEST-001, TEST-002)
- Strengthen test_exception_does_not_crash to assert full body values (TEST-003)

Related to AYG-68

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

---------

Co-authored-by: Aygentic <noreply@aygentic.com>
…y [skip ci] (#5)

- Create docs/api/endpoints/health.md with full schema docs for /healthz,
  /readyz, and /version including Kubernetes probe YAML examples
- Update docs/api/overview.md to add "Operational Endpoints" section at
  root level and mark legacy /utils/health-check/ as superseded
- Update docs/testing/test-registry.md: add 17 health integration tests,
  coverage 188 → 205 total

Related to AYG-68

🤖 Generated by Aygentic

Co-authored-by: Aygentic <noreply@aygentic.com>
…n [AYG-69] (#6)

* feat(entity): add Entity models, service layer, and database migration [AYG-69]

Implements the entity resource foundation for the microservice starter template:

- Pure Pydantic models: EntityBase, EntityCreate, EntityUpdate, EntityPublic,
  EntitiesPublic with field validation (title 1-255 chars, description <= 1000)
- Service layer with CRUD operations via supabase-py table builder pattern:
  create_entity, get_entity, list_entities, update_entity, delete_entity
- All operations enforce ownership via owner_id filtering
- Pagination with offset/limit (capped at 100, clamped to valid range)
- Structured error handling: APIError → 404, infrastructure errors → 500
- Generic error messages (no exception details leaked to clients)
- Supabase SQL migration: entities table, owner index, updated_at trigger,
  RLS policies with WITH CHECK on UPDATE
- 34 unit tests covering happy paths, edge cases, and error handling

Fixes AYG-69
Related to AYG-64

Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

* docs(project): update documentation for entity models and service layer [skip ci]

Updated 6 docs, created 2 new docs based on AYG-69 code changes:
- Data models: entities table, schema family, migration history
- Architecture: service layer component, Entity CRUD flow diagram, ADR-0004
- API: pre-scaffolded entity endpoints (planned for AYG-70)
- Deployment: Supabase CLI migrations section
- Testing: 34 new test entries in test-registry

Related to AYG-69

Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>

---------

Co-authored-by: Aygentic <noreply@aygentic.com>
…YG-70]

Add 5 thin route handlers (POST/GET/GET/{id}/PATCH/{id}/DELETE/{id})
for the Entity resource at /api/v1/entities. All endpoints require
Clerk JWT authentication via PrincipalDep and delegate business logic
to entity_service. Pagination validated at route layer via Query
constraints (offset>=0, limit 1-100). Includes 22 integration tests
covering CRUD lifecycle, auth enforcement, ownership isolation (404
not 403), validation errors, and pagination boundary rejection.

Files:
- CREATE backend/app/api/routes/entities.py (5 route handlers)
- MODIFY backend/app/api/main.py (register entities router)
- CREATE backend/tests/integration/test_entities.py (22 tests)

Fixes AYG-70
Related to AYG-64

🤖 Generated by Aygentic

Co-Authored-By: Aygentic <noreply@aygentic.com>
@amostt
Copy link
Author

amostt commented Feb 28, 2026

Opened against wrong repo — closing.

@amostt amostt closed this Feb 28, 2026
@amostt amostt deleted the amos/ayg-70-entity-api-endpoints-r2 branch February 28, 2026 08:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant