A REST API for appointment booking. Providers publish time slots, clients book and cancel them, and admins manage accounts and service categories.
The API isn't tied to one medical field. Doctors belong to specialties, and admins create those as plain categories at runtime, so the same API works for a general practice, a dental office, a physiotherapy center, or any provider who books by time slot.
Built with Node.js, Express 5, PostgreSQL and Prisma 7. It is covered by 189 tests that run against a real PostgreSQL database, with no mocks, at ~98% line coverage.
- Features
- Tech Stack & Dependencies
- Architecture
- Getting Started
- Environment Variables
- API Overview
- Testing
- Project Structure
- Documentation
Authentication and sessions
- JWT access tokens (15 min) plus opaque refresh tokens (30 days). Refresh tokens are stored only as SHA-256 hashes.
- Refresh tokens rotate on every use. Reusing a token that was already rotated revokes the whole token family (theft detection).
- The account locks for 15 minutes after 5 failed logins. Every login failure returns the same
401, so the API never reveals which emails are registered. - Per-IP rate limiting on
login,registerandrefresh.
Authorization
- Three roles:
ADMIN,DOCTOR(provider) andPATIENT(client). - Role checks run in middleware, and ownership checks run in the service layer. A user can never read or change another user's resources.
- Deactivated accounts are rejected on every protected request, and all of their refresh tokens are revoked right away.
- Deactivated doctors disappear from the public directory, and their slots can't be booked.
- An admin can't deactivate their own account, so the system can't be left without an active admin by accident.
Scheduling and booking
- Doctors create their own availability slots. Overlapping slots are rejected, adjacent slots are allowed, and slots that have already started are refused.
- A slot that has already started can't be booked.
- Booking happens inside a database transaction that atomically claims the slot. Two simultaneous requests for the same slot give exactly one
201and one409. - Appointments follow a state machine:
PENDING → CONFIRMED → COMPLETED.CANCELLEDcan be reached fromPENDINGorCONFIRMED. - Cancelling releases the slot so it can be booked again, and the cancelled appointment stays in the history.
- Past appointments can't be changed, judged by clinic time (
Africa/Cairo, DST-aware). The one exception: a doctor can still mark a past confirmed appointment as completed.
Database integrity checks (these hold even if application code is bypassed)
- A partial unique index allows only one non-cancelled appointment per slot (
WHERE status <> 'CANCELLED'). - A
CHECK (end_time > start_time)constraint on availability.
Platform
- Zod validation for every request and for the environment config at startup.
- One consistent JSON shape for success and error responses, handled by a central error handler.
- Swagger UI at
/api/docsand the OpenAPI 3.0 spec at/api/docs.json. - Helmet security headers, configurable CORS, and graceful shutdown on
SIGTERM/SIGINT.
| Layer | Technology |
|---|---|
| Runtime | Node.js ≥ 20.19 (developed and tested on 24.21), ES Modules |
| Framework | Express 5 |
| Database | PostgreSQL 13+ (developed and tested on 18.6) |
| ORM | Prisma 7 with the pg driver adapter |
| Validation | Zod 4 |
| Auth | jsonwebtoken + bcrypt |
| Testing | node:test (built-in runner) + Supertest |
| Package | Version | Purpose |
|---|---|---|
express |
5.2.1 | HTTP server and routing |
@prisma/client |
7.9.1 | Generated, type-safe database client |
@prisma/adapter-pg |
7.9.1 | Prisma driver adapter for pg |
pg |
8.23.0 | PostgreSQL driver |
zod |
4.4.3 | Request and environment validation |
jsonwebtoken |
9.0.3 | Signing and verifying access tokens |
bcrypt |
6.0.0 | Password hashing |
helmet |
8.3.0 | Security HTTP headers |
cors |
2.8.6 | Cross-origin policy |
cookie-parser |
1.4.7 | Cookie parsing |
rate-limiter-flexible |
11.2.0 | Per-IP rate limiting on auth routes |
swagger-ui-express |
5.0.1 | Interactive API docs |
dotenv |
17.4.2 | Loads .env |
nodemon |
3.1.14 | Auto-reload in development |
| Package | Version | Purpose |
|---|---|---|
prisma |
7.9.1 | Prisma CLI (migrations, client generation) |
supertest |
7.2.2 | HTTP assertions in integration tests |
@types/node |
26.2.0 | Node type definitions (editor support) |
A layered Express application. Each layer talks only to the layer below it:
Request
→ Middleware (helmet, cors, logger, JSON parser)
→ Route (authenticate → requireRole → validate[Zod])
→ Controller (HTTP in/out only)
→ Service (business rules, ownership, state machine, transactions)
→ Repository (thin Prisma wrappers, optional transaction client)
→ Prisma → PostgreSQL
↳ errors bubble to the central error middleware → consistent JSON error
Data model: User (1–1) Doctor | Patient. Specialty (1–N) Doctor. Doctor (1–N) Availability. Availability (1–N) Appointment, with only one of them active. User (1–N) RefreshToken.
See docs/ARCHITECTURE.md and docs/DATABASE.md for the full design.
- Node.js 20.19+ and npm
- A running PostgreSQL server (13+)
git clone https://github.com/omarmoashraf/Clinic-Booking-System-API.git
cd Clinic-Booking-System-API
npm installThe test suite creates its own test database on first run, so the database role needs CREATEDB:
-- run in psql as a superuser
CREATE ROLE clinic_app WITH LOGIN PASSWORD 'Clinic@2026' CREATEDB;
CREATE DATABASE clinic_booking OWNER clinic_app;cp .env.example .env
# then set DATABASE_URL and a JWT_SECRET of 32+ charactersnpx prisma migrate deploy # applies prisma/migrations to the database
npx prisma generate # generates the client into src/generated/prisma
src/generated/is git-ignored, so runnpx prisma generateafter every fresh clone and every schema change.
Admins can't sign up through the public API. Create one with the local bootstrap script, which refuses to run when NODE_ENV=production:
ADMIN_EMAIL=admin@example.com ADMIN_PASSWORD='a-strong-password' ADMIN_FULL_NAME='System Admin' npm run create-adminnpm run dev # development, auto-reloads with nodemon
npm start # plain node
npm run test:db # checks that the database connection worksThe API listens on http://localhost:3000:
| URL | Description |
|---|---|
http://localhost:3000/api/v1/health |
Health check |
http://localhost:3000/api/docs |
Swagger UI |
http://localhost:3000/api/docs.json |
OpenAPI 3.0 spec |
| Script | What it does |
|---|---|
npm run dev |
Starts the server with nodemon |
npm start |
Starts the server with node |
npm test |
Runs the full integration test suite against the test database |
npm run test:coverage |
Same suite with a line, branch and function coverage report |
npm run test:db |
Checks that Prisma can reach DATABASE_URL |
npm run create-admin |
Creates an ADMIN account from env variables |
npm run export:docs |
Writes the OpenAPI spec to docs/openapi.json |
.env.example:
# Server Environment
NODE_ENV=development
PORT=3000
# Database Configuration (PostgreSQL)
DATABASE_URL="postgresql://clinic_app:Clinic%402026@localhost:5432/clinic_booking"
# JWT Authentication
# Must be at least 32 characters long
JWT_SECRET="replace-with-a-secure-random-secret-key-min-32-chars"
JWT_ACCESS_EXPIRES_IN="15m"
JWT_REFRESH_EXPIRES_IN="30d"
# CORS Configuration
# Comma-separated list of allowed origins, or '*' for local testing
CORS_ORIGIN="*"
# Rate Limiting (per IP window)
RATE_LIMIT_LOGIN_MAX="10" # 10 requests per 15 minutes
RATE_LIMIT_REGISTER_MAX="5" # 5 requests per 1 hour
RATE_LIMIT_REFRESH_MAX="20" # 20 requests per 15 minutes| Variable | Required | Default | Notes |
|---|---|---|---|
NODE_ENV |
no | development |
development | test | production |
PORT |
no | 3000 |
1–65535 |
DATABASE_URL |
yes | — | PostgreSQL connection URL. URL-encode special characters (@ → %40) |
JWT_SECRET |
yes | — | At least 32 characters |
JWT_ACCESS_EXPIRES_IN |
no | 15m |
Access token lifetime |
JWT_REFRESH_EXPIRES_IN |
no | 30d |
Format <n>s|m|h|d |
CORS_ORIGIN |
no | * |
Allowed frontend origin(s) |
RATE_LIMIT_*_MAX |
no | 10 / 5 / 20 |
Requests per window, per IP |
All variables are validated with Zod at startup. If a value is invalid, the process prints the errors and exits.
.env.test is committed on purpose. It points to a separate clinic_booking_test database and contains only throwaway local values.
Base path: /api/v1. Protected routes need Authorization: Bearer <accessToken>.
| Method | Endpoint | Access |
|---|---|---|
POST |
/auth/register |
Public (role PATIENT or DOCTOR) |
POST |
/auth/login |
Public |
POST |
/auth/refresh |
Public (refresh token in body) |
POST |
/auth/logout |
Authenticated |
GET |
/users/me |
Authenticated |
PATCH |
/patients/me |
Patient |
GET |
/specialties · /specialties/:id |
Public |
POST · PATCH · DELETE |
/specialties · /specialties/:id |
Admin |
GET |
/doctors · /doctors/:id |
Public (filter by specialty, paginated) |
PATCH |
/doctors/me |
Doctor |
GET |
/doctors/:doctorId/availability |
Public (from / to date filters) |
POST · DELETE |
/doctors/me/availability · /doctors/me/availability/:id |
Doctor |
POST |
/appointments |
Patient |
GET |
/appointments/me |
Patient, Doctor |
GET |
/appointments/:id |
Owner patient or doctor, Admin |
PATCH |
/appointments/:id/status |
Patient (cancel), Doctor (confirm / complete / cancel) |
GET · PATCH |
/admin/users · /admin/users/:id |
Admin |
GET |
/admin/appointments |
Admin (read-only) |
Response format
{ "status": "success", "data": { ... } }
{ "status": "conflict", "message": "Appointment slot is already booked" }
{ "status": "validation_error", "message": "Request validation failed",
"errors": [{ "field": "email", "message": "must be a valid email" }] }On errors, status names the error type: validation_error, unauthorized, forbidden, not_found, conflict or error. In production, unexpected 500 errors never expose their real message or a stack trace.
Typical flow: register → log in → (doctor) create availability slots → (patient) browse doctors and their free slots → book → doctor confirms → doctor completes. Either side can cancel before the slot starts.
The full request and response specification is in docs/API.md. You can try every endpoint live in Swagger UI.
189 tests in 50 suites, all passing (about 50 s). They use Node's built-in test runner (node:test + node:assert/strict) and Supertest, and send real HTTP requests to the Express app backed by a real PostgreSQL test database. Nothing is mocked.
Coverage (npm run test:coverage) |
Lines | Branches | Functions |
|---|---|---|---|
| All source files | 97.9% | 92.4% | 94.7% |
npm test # full suite
npm run test:coverage # full suite + coverage report
node --env-file=.env.test --test tests/auth/login.test.js # one file
node --env-file=.env.test --test --test-name-pattern="concurrent" "tests/**/*.test.js"Isolation: npm test loads .env.test, which points to clinic_booking_test. The helper in tests/helpers/db.js creates that database if it's missing, runs prisma migrate deploy, and truncates every table before each suite. Your development data is never touched.
| Area | Tests | Highlights |
|---|---|---|
| Appointments | 44 | Booking, ownership, no booking of past slots or of deactivated doctors' slots, every valid and invalid status transition, cancel-and-rebook, past-appointment rules in clinic time, a concurrent double-booking race (exactly one succeeds), the partial unique index enforced even when services are bypassed |
| Specialties | 28 | Public listing with pagination and case-insensitive search, admin CRUD, 409 on duplicate names, blocked deletion while doctors are assigned, concurrent duplicate creation |
| Availability | 28 | Creating slots, no slots in the past, overlap rules (same doctor and same date only), from/to range filters, booked slots never exposed, deletion rules, 404 for a deactivated doctor, the DB CHECK constraint enforced even when services are bypassed |
| Doctors | 23 | Public directory with pagination and specialty filters, deactivated doctors hidden and shown again after reactivation, self-service profile updates, unknown fields ignored, profile ownership |
Patients and /users/me |
19 | Profile updates, date-of-birth with no timezone drift, role-specific merged profile, sensitive fields never exposed |
| Auth | 20 | Register (patient and doctor), login, the same generic 401 for every failure, refresh rotation, reuse detection revoking the token family, concurrent refresh race, expired and unknown tokens, logout revoking the session chain, 5-attempt lockout and its expiry |
| Middleware | 13 | authenticate (missing, malformed, invalid and expired tokens, deactivated user), requireRole, and the error handler in production mode (hidden 500 details, Prisma error mapping) |
| Admin | 8 | User listing and filters, updates, deactivation revoking all refresh tokens, no self-deactivation, admin-only access |
| Docs and security | 6 | OpenAPI JSON and Swagger UI are served, Helmet and CORS headers are present, 429 from the login, register and refresh rate limiters |
├── prisma/
│ ├── schema.prisma # Data model
│ └── migrations/ # SQL migrations (incl. CHECK constraint & partial unique index)
├── src/
│ ├── app.js # Express app + server bootstrap & graceful shutdown
│ ├── config/ # Zod-validated environment config
│ ├── routes/ # Route definitions (auth → role → validate → controller)
│ ├── controllers/ # HTTP handlers
│ ├── services/ # Business logic, ownership, state machine, transactions
│ ├── repositories/ # Prisma data access
│ ├── validators/ # Zod request schemas
│ ├── middlewares/ # auth, role, validate, rate-limit, logging, error
│ ├── errors/ # AppError hierarchy
│ ├── utils/ # JWT, hashing, clinic-time (timezone) helpers
│ ├── docs/openapi.js # OpenAPI 3.0 spec served by Swagger UI
│ ├── scripts/ # create-admin, export-docs
│ └── lib/prisma.js # Prisma client singleton
├── tests/ # Integration tests grouped by module + helpers
├── docs/ # PRD, API, architecture & database docs, OpenAPI JSON
├── .env.example
├── .env.test
└── prisma.config.ts
| Document | Contents |
|---|---|
docs/PRD.md |
Product requirements: roles, user flows, business rules, operational decisions, out of scope |
docs/API.md |
Endpoint specification: request and response shapes, validation rules, authorization matrix, error codes |
docs/ARCHITECTURE.md |
Layers, request lifecycle, how authentication, authorization and error handling are designed |
docs/DATABASE.md |
Tables, relations, constraints, indexes, ERD, design decisions |
docs/openapi.json |
OpenAPI 3.0 spec for Postman, client code generation or a frontend (regenerate with npm run export:docs) |