# Backend Specification — Template

> **How to use this file:** This is a *reference template*. Give it to Claude Code along with your `project-overview.md`, and ask it to produce a filled-in `backend-spec.md` that follows this structure for *your* project and *your* chosen stack. Keep the section headings; replace the guidance with real content. This file is technology-agnostic on purpose — it describes *what* the backend must define, and lets you (or the AI) commit to a specific framework, language, and database.
>
> The point of writing this before coding: the backend is where the rules live. If the data model, the endpoints, and the validation are specified clearly up front, the AI builds something coherent instead of guessing at structure and having to be corrected ten times.

---

## 1. Stack & conventions

State the concrete choices for this project:

- **Language / framework:** (e.g. Node.js + Express, Spring Boot, Django, …)
- **Database:** (e.g. PostgreSQL, MySQL, MongoDB, SQLite)
- **API style:** (REST, GraphQL, RPC)
- **Auth method:** (JWT, session, OAuth, none for now)
- **Conventions:** naming (camelCase/snake_case), error format, date/time handling (store UTC), money handling (smallest unit), ID strategy (UUID/auto-increment)

Write these down once here so every endpoint below inherits them.

---

## 2. Data model (full schema)

For each entity, define the real fields. This is the source of truth for the database.

**For every table/collection, specify:**
- Name
- Each field: name, type, required?, default, constraints (unique, min/max, enum values)
- Primary key
- Foreign keys / relationships and their cardinality (one-to-many, many-to-many)
- Indexes that matter for performance
- Timestamps (created_at, updated_at) if used

*Example (fill with your real entities):*

**`customers`**
| field | type | required | notes |
|-------|------|----------|-------|
| id | UUID | yes | primary key |
| name | string | yes | max 120 chars |
| phone | string | yes | unique |
| created_at | timestamp | yes | default now (UTC) |

Relationships: a `customer` has many `bookings` (one-to-many via `bookings.customer_id`).

Repeat for every entity in the system.

---

## 3. API endpoints

Define every endpoint the frontend (or other clients) will call. Group them by resource.

**For each endpoint, specify:**
- Method + path (e.g. `POST /api/customers`)
- What it does (one line)
- Auth required? Which role?
- Request: path params, query params, body shape (with types)
- Response: success shape + status code
- Error cases: what can go wrong and which status code each returns
- Validation rules applied to the input

*Example:*

### `POST /api/bookings`
- **Purpose:** Create a new booking
- **Auth:** required (customer or business)
- **Body:**
  ```json
  {
    "serviceId": "uuid",
    "customerId": "uuid",
    "startTime": "ISO 8601 datetime (UTC)"
  }
  ```
- **Success:** `201 Created` → the created booking object
- **Errors:**
  - `400` — missing/invalid fields
  - `409` — time slot already booked
  - `404` — service or customer not found
- **Validation:** startTime must be in the future; slot must be free

List every endpoint this way. Don't leave "obvious" ones implicit — the AI will fill gaps with assumptions if you do.

---

## 4. Business logic & rules

The non-CRUD logic — the rules that make this product what it is. Describe each rule clearly enough that it could be turned into a test.

*Examples:*
- **No double-booking:** before creating a booking, check no existing booking overlaps the same resource and time range.
- **Cancellation window:** a booking can only be cancelled more than X hours before start time.
- **Pricing:** total = service price; store in smallest currency unit; never compute money in floats.

For each rule, note *where* it lives (which endpoint/service enforces it) so it isn't duplicated or forgotten.

---

## 5. Validation & error handling

- **Input validation:** the general approach (validate at the boundary, reject early).
- **Error response format:** one consistent shape for all errors, e.g.
  ```json
  { "error": { "code": "SLOT_TAKEN", "message": "That time is no longer available." } }
  ```
- **Status code conventions:** which codes you use and when.

---

## 6. Auth & permissions

- How a user authenticates
- How the backend knows who the user is on each request
- The permission rules: who can read/write what (e.g. "a customer can only see their own bookings")
- Any roles and what each role can do

---

## 7. External integrations

For each third-party service (payments, messaging, email, storage, etc.):
- What it's used for
- Which operations call it
- What happens if it fails (retry? queue? surface an error?)
- Where credentials live (env vars — never hardcoded)

---

## 8. Non-functional requirements

- Performance expectations (e.g. list endpoints paginated, page size)
- Rate limiting, if any
- Logging: what to log, what never to log (no secrets, no full PII)
- Environment config: what's driven by environment variables

---

## 9. Build order

Suggest the order in which to build, so the AI works in dependency order rather than jumping around:
1. Data model / migrations
2. Core CRUD endpoints per entity
3. Business-logic endpoints
4. Auth & permissions
5. External integrations
6. Validation hardening & error consistency

---

### Reminder for the AI reading this

When you generate the real `backend-spec.md`:
- Commit to the project's actual stack from section 1 and use it consistently.
- Define every entity and every endpoint fully — no placeholders.
- Any decision not given to you goes into an "Open questions" note, not a silent assumption.
- Keep money, dates, and IDs handled per the conventions, everywhere.
