Planned HTTP APIs for the portal.
Project Name: Kifuliiru Public API Version: 1.0 Date: January 29, 2026 Status: Planning
Transform the Kifuliiru website into a public API host that exposes language and cultural data to:
Create an open, well-documented API that makes the Kifuliiru language accessible to developers worldwide, enabling the creation of educational apps, language learning tools, and cultural preservation projects.
| Aspect | Description | |--------|-------------| | Category | REST API Development | | Architecture | Next.js API Routes with Supabase Backend | | Access Model | API Key Authentication | | Documentation | Interactive Swagger/OpenAPI at /api/docs | | Versioning | URL-based (/api/v1/) |
| Component | Status | Notes | |-----------|--------|-------| | Database (Supabase) | Ready | PostgreSQL with 15+ tables of language data | | User Authentication | Ready | Supabase Auth with JWT | | Basic API Routes | Partial | 22 routes exist but inconsistent format | | Data Content | Ready | Numbers, proverbs, vocabulary, verbs, cultural data |
| Table | Content | Records | |-------|---------|---------| | magambo | Dictionary words | Available | | kuharura | Number system | Available | | imigani | Proverbs | Available | | verbs | Verb conjugations | Available | | people | Notable people | Available | | villages | Village data | Available | | animals | Animal names | Available | | trees | Tree names | Available | | herbs | Medicinal herbs | Available | | mountains | Mountain names | Available | | rivers | River names | Available | | abaami | Historical leaders | Available |
| Requirement | Purpose | Priority | |-------------|---------|----------| | API Key Management System | Authenticate developer requests | High | | Rate Limiting | Prevent abuse, ensure fair usage | High | | Request Logging | Track usage, debug issues | High | | CORS Configuration | Allow cross-origin requests | High | | Error Handling Middleware | Consistent error responses | High | | Response Caching | Improve performance | Medium |
-- New tables needed in Supabase
-- API Keys table
CREATE TABLE api_keys (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
key_hash TEXT NOT NULL UNIQUE,
key_prefix TEXT NOT NULL, -- First 8 chars for identification
name TEXT NOT NULL,
owner_email TEXT NOT NULL,
tier TEXT DEFAULT 'free', -- free, pro, unlimited
rate_limit INTEGER DEFAULT 1000, -- requests per hour
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW(),
last_used_at TIMESTAMP,
total_requests INTEGER DEFAULT 0
);
-- API Usage Logs table
CREATE TABLE api_usage_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
api_key_id UUID REFERENCES api_keys(id),
endpoint TEXT NOT NULL,
method TEXT NOT NULL,
status_code INTEGER,
response_time_ms INTEGER,
ip_address TEXT,
user_agent TEXT,
created_at TIMESTAMP DEFAULT NOW()
);
-- Indexes for performance
CREATE INDEX idx_api_keys_hash ON api_keys(key_hash);
CREATE INDEX idx_api_keys_prefix ON api_keys(key_prefix);
CREATE INDEX idx_usage_logs_key_id ON api_usage_logs(api_key_id);
CREATE INDEX idx_usage_logs_created ON api_usage_logs(created_at);
```text
### 3. Dependencies to Install
```json
{
"dependencies": {
"swagger-ui-react": "^5.x", // API documentation UI
"openapi-types": "^12.x", // TypeScript types for OpenAPI
"nanoid": "^5.x", // Generate API keys
"rate-limiter-flexible": "^5.x" // Rate limiting
}
}
```text
---
## What's Going to Be Done
### Phase 1: Foundation (Core Infrastructure)
#### 1.1 API Key System
**Files to create:**
- `src/lib/apiKeyService.ts` - Key generation, validation, hashing
- `src/app/api/v1/auth/register/route.ts` - Developer registration
- `src/app/api/v1/auth/verify/route.ts` - Key verification endpoint
**Features:**
- Generate secure API keys (format: `kfl_live_xxxxxxxxxxxx`)
- Hash keys before storing (only store hash, not plaintext)
- Validate keys on each request
- Track usage per key
#### 1.2 Middleware Layer
**Files to create:**
- `src/middleware/apiAuth.ts` - API key validation
- `src/middleware/rateLimit.ts` - Rate limiting logic
- `src/middleware/apiResponse.ts` - Standard response wrapper
- `src/middleware/cors.ts` - CORS configuration
**Features:**
- Validate `X-API-Key` header on all `/api/v1/*` routes
- Enforce rate limits (1000 req/hour free, 10000 req/hour pro)
- Wrap all responses in consistent format
- Allow cross-origin requests with proper headers
#### 1.3 Standard Response Format
**Success Response:**
```json
{
"success": true,
"data": { ... },
"pagination": {
"page": 1,
"limit": 20,
"total": 150,
"total_pages": 8,
"has_next": true,
"has_prev": false
},
"meta": {
"api_version": "1.0",
"request_id": "req_abc123",
"timestamp": "2026-01-29T10:30:00Z"
}
}
```text
**Error Response:**
```json
{
"success": false,
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "You have exceeded your rate limit of 1000 requests per hour",
"details": {
"limit": 1000,
"remaining": 0,
"reset_at": "2026-01-29T11:00:00Z"
}
},
"meta": {
"api_version": "1.0",
"request_id": "req_abc123",
"timestamp": "2026-01-29T10:30:00Z"
}
}
```text
---
### Phase 2: API Endpoints
#### 2.1 Endpoint Structure
```text
/api/v1/
│
├── /auth/
│ ├── POST /register → Register for API key
│ └── GET /verify → Verify API key status
│
├── /dictionary/
│ ├── GET / → List words (paginated)
│ ├── GET /:id → Get single word
│ └── GET /search → Search words
│
├── /numbers/
│ ├── GET / → List number translations
│ ├── GET /:number → Get specific number
│ └── GET /range → Get range (e.g., 1-100)
│
├── /proverbs/
│ ├── GET / → List proverbs (paginated)
│ ├── GET /:id → Get single proverb
│ ├── GET /random → Get random proverb
│ └── GET /search → Search proverbs
│
├── /vocabulary/
│ ├── GET / → List vocabulary sets
│ ├── GET /:category → Get by category
│ └── GET /search → Search vocabulary
│
├── /verbs/
│ ├── GET / → List verbs
│ ├── GET /:id → Get verb with conjugations
│ └── GET /search → Search verbs
│
├── /culture/
│ ├── GET /people → Notable people
│ ├── GET /villages → Villages
│ ├── GET /animals → Animal names
│ ├── GET /trees → Tree names
│ ├── GET /herbs → Medicinal herbs
│ ├── GET /mountains → Mountains
│ ├── GET /rivers → Rivers
│ └── GET /leaders → Historical leaders (abaami)
│
├── /search/
│ └── GET / → Global search across all content
│
└── /stats/
└── GET / → API and content statistics
```text
#### 2.2 Files to Create
| Path | Purpose | |------|---------| | `src/app/api/v1/auth/register/route.ts` | Developer registration | | `src/app/api/v1/auth/verify/route.ts` | Key verification | | `src/app/api/v1/dictionary/route.ts` | Dictionary list | | `src/app/api/v1/dictionary/[id]/route.ts` | Single word | | `src/app/api/v1/dictionary/search/route.ts` | Word search | | `src/app/api/v1/numbers/route.ts` | Numbers list | | `src/app/api/v1/numbers/[number]/route.ts` | Single number | | `src/app/api/v1/numbers/range/route.ts` | Number range | | `src/app/api/v1/proverbs/route.ts` | Proverbs list | | `src/app/api/v1/proverbs/[id]/route.ts` | Single proverb | | `src/app/api/v1/proverbs/random/route.ts` | Random proverb | | `src/app/api/v1/proverbs/search/route.ts` | Proverb search | | `src/app/api/v1/vocabulary/route.ts` | Vocabulary list | | `src/app/api/v1/vocabulary/[category]/route.ts` | By category | | `src/app/api/v1/verbs/route.ts` | Verbs list | | `src/app/api/v1/verbs/[id]/route.ts` | Single verb | | `src/app/api/v1/culture/[type]/route.ts` | Cultural data | | `src/app/api/v1/search/route.ts` | Global search | | `src/app/api/v1/stats/route.ts` | Statistics |
---
### Phase 3: Documentation
#### 3.1 OpenAPI Specification
**File:** `src/app/api/v1/openapi.json`
Complete OpenAPI 3.0 specification documenting:
- All endpoints with parameters
- Request/response schemas
- Authentication requirements
- Error codes and messages
- Example requests and responses
#### 3.2 Interactive Documentation UI
**Files:**
- `src/app/api/docs/page.tsx` - Swagger UI page
- `src/components/api-docs/ApiDocumentation.tsx` - Documentation component
**Features:**
- Beautiful, interactive documentation
- "Try it out" functionality
- Code examples in multiple languages (curl, JavaScript, Python)
- Authentication helper
#### 3.3 Developer Portal Page
**File:** `src/app/developers/page.tsx`
**Content:**
- Overview of the API
- Quick start guide
- API key registration form
- Usage examples
- Rate limits explanation
- Terms of use
---
### Phase 4: Security & Performance
#### 4.1 Security Measures
| Measure | Implementation | |---------|----------------| | Key Hashing | SHA-256 hash before storage | | Rate Limiting | Per-key limits with sliding window | | Input Validation | Zod schemas on all endpoints | | SQL Injection Prevention | Parameterized queries (Supabase handles this) | | HTTPS Only | Enforced in production | | Key Rotation | Ability to regenerate compromised keys |
#### 4.2 Performance Optimizations
| Optimization | Implementation | |--------------|----------------| | Response Caching | Cache-Control headers for GET requests | | Database Indexing | Indexes on frequently queried columns | | Pagination | Required on all list endpoints | | Query Limits | Max 100 items per request | | Compression | Gzip responses |
---
## API Key Tiers
| Tier | Rate Limit | Features | Price | |------|------------|----------|-------| | **Free** | 1,000 req/hour | All read endpoints | Free | | **Pro** | 10,000 req/hour | All endpoints + priority support | TBD | | **Unlimited** | No limit | Enterprise features | Contact |
---
## Success Metrics
| Metric | Target | |--------|--------| | API Response Time | < 200ms average | | Uptime | 99.9% | | Documentation Coverage | 100% of endpoints | | Developer Adoption | Track registrations |
---
## Timeline Estimate
| Phase | Scope | |-------|-------| | Phase 1 | Foundation (Auth, Middleware, Response Format) | | Phase 2 | API Endpoints (All v1 routes) | | Phase 3 | Documentation (OpenAPI, Swagger UI, Developer Portal) | | Phase 4 | Security & Performance (Hardening, Optimization) |
---
## File Structure After Implementation
```text
src/
├── app/
│ ├── api/
│ │ ├── v1/
│ │ │ ├── auth/
│ │ │ │ ├── register/route.ts
│ │ │ │ └── verify/route.ts
│ │ │ ├── dictionary/
│ │ │ │ ├── route.ts
│ │ │ │ ├── [id]/route.ts
│ │ │ │ └── search/route.ts
│ │ │ ├── numbers/
│ │ │ │ ├── route.ts
│ │ │ │ ├── [number]/route.ts
│ │ │ │ └── range/route.ts
│ │ │ ├── proverbs/
│ │ │ │ ├── route.ts
│ │ │ │ ├── [id]/route.ts
│ │ │ │ ├── random/route.ts
│ │ │ │ └── search/route.ts
│ │ │ ├── vocabulary/
│ │ │ │ ├── route.ts
│ │ │ │ └── [category]/route.ts
│ │ │ ├── verbs/
│ │ │ │ ├── route.ts
│ │ │ │ └── [id]/route.ts
│ │ │ ├── culture/
│ │ │ │ └── [type]/route.ts
│ │ │ ├── search/route.ts
│ │ │ ├── stats/route.ts
│ │ │ └── openapi.json
│ │ └── docs/
│ │ └── page.tsx
│ └── developers/
│ └── page.tsx
├── lib/
│ ├── api/
│ │ ├── apiKeyService.ts
│ │ ├── rateLimiter.ts
│ │ ├── responseHelper.ts
│ │ └── validation.ts
│ └── middleware/
│ ├── apiAuth.ts
│ ├── rateLimit.ts
│ └── cors.ts
├── components/
│ └── api-docs/
│ └── ApiDocumentation.tsx
└── types/
└── api.ts
```text
---
## Next Steps
1. **Review this document** - Confirm scope and approach
2. **Set up database tables** - Create api_keys and api_usage_logs in Supabase
3. **Begin Phase 1** - Build foundation (auth, middleware)
4. **Iterate** - Build endpoints, test, document
---
## Approval
- [ ] Project scope approved
- [ ] Database schema approved
- [ ] API structure approved
- [ ] Ready to begin implementation
---
*Document created: January 29, 2026*
*Last updated: January 29, 2026*