# Rental Platform API Documentation

## Table of Contents
- [Overview](#overview)
- [Base URL](#base-url)
- [Authentication](#authentication)
- [Rate Limiting](#rate-limiting)
- [Response Format](#response-format)
- [Error Handling](#error-handling)
- [Endpoints](#endpoints)
  - [General](#general-endpoints)
  - [Authentication](#authentication-endpoints)

---

## Overview

The Rental Platform API is a RESTful API for managing car and house rentals. This API provides user authentication, property listings, and rental management functionality.

**Current Version:** 1.0.0  
**Environment:** Development  
**Database:** SQLite (Development) / PostgreSQL (Production)

---

## Base URL

**Development:**
```
http://127.0.0.1:5000
```

**Production:**
```
https://your-domain.com
```

---

## Authentication

The API uses **JWT (JSON Web Tokens)** for authentication. After successful login or email verification, you'll receive two tokens:

- **Access Token** - Valid for 1 hour, used for API requests
- **Refresh Token** - Valid for 1 day, used to get new access tokens

### Using Access Tokens

Include the access token in the `Authorization` header of your requests:

```http
Authorization: Bearer <your_access_token>
```

### Example:
```bash
curl -X GET http://127.0.0.1:5000/protected-endpoint \
  -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc..."
```

---

## Rate Limiting

All endpoints are rate-limited to prevent abuse. Rate limits are applied per IP address per hour.

| Endpoint | Rate Limit |
|----------|------------|
| POST /auth/register | 5 per hour |
| POST /auth/verify-email | 10 per hour |
| POST /auth/login | 10 per hour |
| POST /auth/resend-code | 3 per hour |
| POST /auth/refresh-token | 20 per hour |

**Rate Limit Headers:**
```http
X-RateLimit-Limit: 5
X-RateLimit-Remaining: 4
X-RateLimit-Reset: 1234567890
```

**Rate Limit Exceeded Response (429):**
```json
{
  "error": "Rate Limit Exceeded",
  "message": "Too many requests. Please try again later."
}
```

---

## Response Format

All API responses follow a consistent JSON format:

### Success Response:
```json
{
  "success": true,
  "message": "Operation completed successfully",
  "data": {
    // Response data here
  }
}
```

### Error Response:
```json
{
  "success": false,
  "message": "Error description",
  "data": null
}
```

---

## Error Handling

### HTTP Status Codes

| Code | Meaning | Description |
|------|---------|-------------|
| 200 | OK | Request successful |
| 201 | Created | Resource created successfully |
| 400 | Bad Request | Invalid request data |
| 401 | Unauthorized | Authentication failed |
| 404 | Not Found | Resource not found |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error |

### Common Error Responses

**Missing Required Fields (400):**
```json
{
  "success": false,
  "message": "Missing required fields: email, password",
  "data": null
}
```

**Invalid Credentials (401):**
```json
{
  "success": false,
  "message": "Invalid credentials",
  "data": null
}
```

**Resource Not Found (404):**
```json
{
  "error": "Not Found",
  "message": "The requested resource was not found"
}
```

---

## Endpoints

### General Endpoints

#### Get Welcome Message
Returns API welcome message and status.

**Endpoint:** `GET /`

**Authentication:** Not required

**Example Request:**
```bash
curl -X GET http://127.0.0.1:5000/
```

**Example Response (200 OK):**
```json
{
  "message": "Welcome to the Rental Platform API",
  "version": "1.0.0",
  "status": "running"
}
```

---

#### Get API Information
Returns API information and available endpoints.

**Endpoint:** `GET /api`

**Authentication:** Not required

**Example Request:**
```bash
curl -X GET http://127.0.0.1:5000/api
```

**Example Response (200 OK):**
```json
{
  "message": "Welcome to the Rental Platform API",
  "version": "1.0.0",
  "endpoints": {
    "auth": "/auth",
    "health": "/health"
  }
}
```

---

#### Health Check
Check API health status.

**Endpoint:** `GET /health`

**Authentication:** Not required

**Example Request:**
```bash
curl -X GET http://127.0.0.1:5000/health
```

**Example Response (200 OK):**
```json
{
  "status": "healthy",
  "database": "connected"
}
```

---

### Authentication Endpoints

#### Register User
Create a new user account. A 6-digit verification code will be sent to the provided email.

**Endpoint:** `POST /auth/register`

**Rate Limit:** 5 requests per hour

**Authentication:** Not required

**Request Body:**
```json
{
  "first_name": "John",
  "last_name": "Doe",
  "username": "johndoe",
  "email": "john@example.com",
  "password": "SecurePass123"
}
```

**Field Requirements:**
- `first_name`: 1-50 characters, required
- `last_name`: 1-50 characters, required
- `username`: 3-50 characters, alphanumeric + underscores, required
- `email`: Valid email format, required
- `password`: Minimum 8 characters, must contain at least one letter and one number, required

**Example Request:**
```bash
curl -X POST http://127.0.0.1:5000/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "John",
    "last_name": "Doe",
    "username": "johndoe",
    "email": "john@example.com",
    "password": "SecurePass123"
  }'
```

**Success Response (201 Created):**
```json
{
  "success": true,
  "message": "Registration successful. Please check your email for verification code.",
  "data": {
    "email": "john@example.com"
  }
}
```

**Error Responses:**

*Email Already Registered (400):*
```json
{
  "success": false,
  "message": "Email already registered",
  "data": null
}
```

*Username Already Taken (400):*
```json
{
  "success": false,
  "message": "Username already taken",
  "data": null
}
```

*Invalid Password (400):*
```json
{
  "success": false,
  "message": "Password must be at least 8 characters long",
  "data": null
}
```

*Invalid Email (400):*
```json
{
  "success": false,
  "message": "The email address is not valid",
  "data": null
}
```

---

#### Verify Email
Verify user email with the 6-digit code sent during registration.

**Endpoint:** `POST /auth/verify-email`

**Rate Limit:** 10 requests per hour

**Authentication:** Not required

**Request Body:**
```json
{
  "email": "john@example.com",
  "code": "123456"
}
```

**Example Request:**
```bash
curl -X POST http://127.0.0.1:5000/auth/verify-email \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "code": "123456"
  }'
```

**Success Response (200 OK):**
```json
{
  "success": true,
  "message": "Email verified successfully",
  "data": {
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "user": {
      "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "username": "johndoe",
      "email": "john@example.com",
      "role": "customer",
      "is_active": true,
      "is_verified": false,
      "is_email_verified": true
    }
  }
}
```

**Error Responses:**

*Invalid Code (400):*
```json
{
  "success": false,
  "message": "Invalid verification code. 3 attempts remaining.",
  "data": null
}
```

*Code Expired (400):*
```json
{
  "success": false,
  "message": "Verification code has expired. Please request a new one.",
  "data": null
}
```

*Too Many Attempts (400):*
```json
{
  "success": false,
  "message": "Too many failed attempts. Please request a new code.",
  "data": null
}
```

*User Not Found (400):*
```json
{
  "success": false,
  "message": "User not found",
  "data": null
}
```

---

#### Login User
Authenticate user with email/username and password.

**Endpoint:** `POST /auth/login`

**Rate Limit:** 10 requests per hour

**Authentication:** Not required

**Request Body:**
```json
{
  "email_or_username": "john@example.com",
  "password": "SecurePass123"
}
```

**Note:** You can use either email or username in the `email_or_username` field.

**Example Request (with email):**
```bash
curl -X POST http://127.0.0.1:5000/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email_or_username": "john@example.com",
    "password": "SecurePass123"
  }'
```

**Example Request (with username):**
```bash
curl -X POST http://127.0.0.1:5000/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email_or_username": "johndoe",
    "password": "SecurePass123"
  }'
```

**Success Response (200 OK):**
```json
{
  "success": true,
  "message": "Login successful",
  "data": {
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "user": {
      "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "username": "johndoe",
      "email": "john@example.com",
      "role": "customer",
      "is_active": true,
      "is_verified": false,
      "is_email_verified": true
    }
  }
}
```

**Error Responses:**

*Invalid Credentials (401):*
```json
{
  "success": false,
  "message": "Invalid credentials",
  "data": null
}
```

*Email Not Verified (400):*
```json
{
  "success": false,
  "message": "Please verify your email before logging in",
  "data": null
}
```

*Account Deactivated (400):*
```json
{
  "success": false,
  "message": "Account is deactivated",
  "data": null
}
```

---

#### Resend Verification Code
Request a new verification code if the previous one expired or was lost.

**Endpoint:** `POST /auth/resend-code`

**Rate Limit:** 3 requests per hour

**Authentication:** Not required

**Request Body:**
```json
{
  "email": "john@example.com"
}
```

**Example Request:**
```bash
curl -X POST http://127.0.0.1:5000/auth/resend-code \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com"
  }'
```

**Success Response (200 OK):**
```json
{
  "success": true,
  "message": "Verification code sent. Please check your email.",
  "data": {
    "email": "john@example.com"
  }
}
```

**Error Responses:**

*Email Already Verified (400):*
```json
{
  "success": false,
  "message": "Email already verified",
  "data": null
}
```

*Rate Limit Exceeded (400):*
```json
{
  "success": false,
  "message": "Too many requests. Please try again later.",
  "data": null
}
```

*User Not Found (400):*
```json
{
  "success": false,
  "message": "User not found",
  "data": null
}
```

---

#### Refresh Access Token
Get a new access token using a valid refresh token.

**Endpoint:** `POST /auth/refresh-token`

**Rate Limit:** 20 requests per hour

**Authentication:** Refresh token required

**Request Body:**
```json
{
  "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
}
```

**Example Request:**
```bash
curl -X POST http://127.0.0.1:5000/auth/refresh-token \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
  }'
```

**Success Response (200 OK):**
```json
{
  "success": true,
  "message": "Token refreshed successfully",
  "data": {
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "user": {
      "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "username": "johndoe",
      "email": "john@example.com",
      "role": "customer",
      "is_active": true,
      "is_verified": false,
      "is_email_verified": true
    }
  }
}
```

**Note:** The response includes updated user data to reflect any profile changes, role upgrades, or verification status updates since the original login.

**Error Responses:**

*Invalid Token (401):*
```json
{
  "success": false,
  "message": "Invalid or expired refresh token",
  "data": null
}
```

*User Inactive (401):*
```json
{
  "success": false,
  "message": "User not found or inactive",
  "data": null
}
```

---

## User Roles

The API supports three user roles:

| Role | Value | Description |
|------|-------|-------------|
| Customer | `customer` | Default role, can browse and rent properties |
| Owner | `owner` | Can list properties for rent |
| Admin | `admin` | Platform administrator with full access |

**Note:** New users are automatically assigned the `customer` role. To become an owner and list properties, users must complete owner verification (future feature).

---

## Email Verification

### Development Mode
In development, verification codes are logged to the console instead of being sent via email:

```
=== EMAIL VERIFICATION CODE ===
To: john@example.com
Code: 123456
===============================
```

### Production Mode
In production, codes are sent via Gmail SMTP. Configure the following environment variables:

```env
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_DEFAULT_SENDER=noreply@yourdomain.com
```

### Code Specifications
- **Format:** 6-digit numeric code (100000-999999)
- **Expiration:** 30 minutes
- **Max Attempts:** 5 tries per code
- **Resend Limit:** 3 requests per hour per email

---

## Token Specifications

### Access Token
- **Purpose:** Authenticate API requests
- **Expiration:** 1 hour
- **Payload:**
```json
{
  "user_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "role": "customer",
  "type": "access",
  "exp": 1234567890,
  "iat": 1234567890
}
```

### Refresh Token
- **Purpose:** Obtain new access tokens
- **Expiration:** 1 day
- **Payload:**
```json
{
  "user_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "type": "refresh",
  "exp": 1234567890,
  "iat": 1234567890
}
```

---

## Complete Authentication Flow

### 1. Registration Flow
```
User submits registration
    ↓
System validates input
    ↓
Creates user (is_email_verified=false)
    ↓
Generates 6-digit code
    ↓
Saves code to database (30 min expiry)
    ↓
Sends code via email
    ↓
Returns success message
```

### 2. Verification Flow
```
User submits email + code
    ↓
System validates code
    ↓
Checks expiry & attempts
    ↓
Sets is_email_verified=true
    ↓
Marks code as used
    ↓
Generates JWT tokens
    ↓
Returns tokens + user data
```

### 3. Login Flow
```
User submits credentials
    ↓
System finds user by email/username
    ↓
Validates password
    ↓
Checks email verification
    ↓
Checks account status
    ↓
Generates JWT tokens
    ↓
Returns tokens + user data
```

### 4. Token Refresh Flow
```
User submits refresh token
    ↓
System validates token
    ↓
Checks user status
    ↓
Generates new access token
    ↓
Returns new access token
```

---

## Best Practices

### Security
1. **Always use HTTPS in production**
2. **Never log or expose passwords**
3. **Store tokens securely** (httpOnly cookies or secure storage)
4. **Implement token rotation** (refresh tokens regularly)
5. **Use strong passwords** (min 8 chars, letters + numbers)

### Error Handling
1. **Check response status codes**
2. **Handle rate limit errors gracefully**
3. **Implement retry logic with exponential backoff**
4. **Display user-friendly error messages**

### Token Management
1. **Store tokens securely** (not in localStorage)
2. **Refresh tokens before expiry**
3. **Clear tokens on logout**
4. **Handle token expiration gracefully**

---

## Testing Examples

### Complete Registration to Login Flow

```bash
# 1. Register new user
curl -X POST http://127.0.0.1:5000/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "Jane",
    "last_name": "Smith",
    "username": "janesmith",
    "email": "jane@example.com",
    "password": "MySecurePass456"
  }'

# Response: Check console logs for verification code

# 2. Verify email (use code from logs)
curl -X POST http://127.0.0.1:5000/auth/verify-email \
  -H "Content-Type: application/json" \
  -d '{
    "email": "jane@example.com",
    "code": "123456"
  }'

# Response: Save access_token and refresh_token

# 3. Login (later)
curl -X POST http://127.0.0.1:5000/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email_or_username": "janesmith",
    "password": "MySecurePass456"
  }'

# Response: New access_token and refresh_token

# 4. Refresh token (when access token expires)
curl -X POST http://127.0.0.1:5000/auth/refresh-token \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "your_refresh_token_here"
  }'

# Response: New access_token
```

---

## Changelog

### Version 1.0.0 (Current)
- ✅ User registration with email verification
- ✅ JWT-based authentication
- ✅ Login with email or username
- ✅ Token refresh mechanism
- ✅ Rate limiting on all endpoints
- ✅ Comprehensive error handling

### Upcoming Features
- User profile management
- Password reset functionality
- Owner verification system
- Property listing (houses & cars)
- Booking/rental management
- Payment integration

---

## Support

For questions, issues, or feature requests, please contact:
- **Email:** support@rentalplatform.com
- **Documentation:** https://docs.rentalplatform.com

---

*Last Updated: December 2025*