# GATE API Reference

Documentation for GATE API Reference

# Overview

> Complete API reference for GATE API with 45 endpoints across 20 categories.

**Version:** v1  
**Base URL:** `https://gate.zequenze.com/api/v1`

Zequenze GATE platform API documentation

---

## Authentication

All API endpoints require authentication using a Bearer token in the request header:

```http
Authorization: Bearer <your-api-token>
```

You can obtain your API token from the portal administration panel.

---

## Available Endpoints

| Category | Endpoints | Methods |
|----------|:---------:|---------|
| [Aaa Accounting](https://docs.zequenze.com/books/gate-api-reference/page/aaa-accounting-k7Z) | 2 | `GET` |
| [Aaa Profile](https://docs.zequenze.com/books/gate-api-reference/page/aaa-profile-M6Z) | 6 | `DELETE` `GET` `PATCH` `POST` `PUT` |
| [Device App Access Devices](https://docs.zequenze.com/books/gate-api-reference/page/device-app-access-devices-HDH) | 1 | `GET` |
| [Device App Access Points](https://docs.zequenze.com/books/gate-api-reference/page/device-app-access-points-5ss) | 1 | `GET` |
| [Device App Connection Log](https://docs.zequenze.com/books/gate-api-reference/page/device-app-connection-log-7uS) | 1 | `POST` |
| [Device App Connection Summary](https://docs.zequenze.com/books/gate-api-reference/page/device-app-connection-summary-i4D) | 1 | `GET` |
| [Device App Locations](https://docs.zequenze.com/books/gate-api-reference/page/device-app-locations-x39) | 1 | `GET` |
| [Device App Register](https://docs.zequenze.com/books/gate-api-reference/page/device-app-register-MLh) | 1 | `POST` |
| [Device App Test Report](https://docs.zequenze.com/books/gate-api-reference/page/device-app-test-report-0Bv) | 1 | `POST` |
| [Device App User Authenticate](https://docs.zequenze.com/books/gate-api-reference/page/device-app-user-authenticate-dUz) | 1 | `POST` |
| [Device App User Update](https://docs.zequenze.com/books/gate-api-reference/page/device-app-user-update-l1W) | 1 | `POST` |
| [Hostspot Access Points](https://docs.zequenze.com/books/gate-api-reference/page/hostspot-access-points-h87) | 1 | `GET` |
| [Hostspot Locations](https://docs.zequenze.com/books/gate-api-reference/page/hostspot-locations-4pw) | 1 | `GET` |
| [Me](https://docs.zequenze.com/books/gate-api-reference/page/me-Vp5) | 1 | `GET` |
| [Organization](https://docs.zequenze.com/books/gate-api-reference/page/organization-OMu) | 1 | `GET` |
| [Portal Login](https://docs.zequenze.com/books/gate-api-reference/page/portal-login-KoR) | 1 | `POST` |
| [Txlog Portal](https://docs.zequenze.com/books/gate-api-reference/page/txlog-portal-8Yf) | 1 | `GET` |
| [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) | 10 | `DELETE` `GET` `PATCH` `POST` `PUT` |
| [User Extra](https://docs.zequenze.com/books/gate-api-reference/page/user-extra-Bk0) | 6 | `DELETE` `GET` `PATCH` `POST` `PUT` |
| [User Token](https://docs.zequenze.com/books/gate-api-reference/page/user-token-7jF) | 6 | `DELETE` `GET` `PATCH` `POST` `PUT` |

---

## All Endpoints

| Method | Path | Documentation |
|:------:|------|---------------|
| `GET` | <a href="https://gate.zequenze.com/api#/aaa_accounting/aaa_accounting_list" target="_blank">`/aaa_accounting/`</a> | [Aaa Accounting](https://docs.zequenze.com/books/gate-api-reference/page/aaa-accounting-k7Z) |
| `GET` | <a href="https://gate.zequenze.com/api#/aaa_accounting/aaa_accounting_read" target="_blank">`/aaa_accounting/{radacctid}/`</a> | [Aaa Accounting](https://docs.zequenze.com/books/gate-api-reference/page/aaa-accounting-k7Z) |
| `GET` | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_list" target="_blank">`/aaa_profile/`</a> | [Aaa Profile](https://docs.zequenze.com/books/gate-api-reference/page/aaa-profile-M6Z) |
| `POST` | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_create" target="_blank">`/aaa_profile/`</a> | [Aaa Profile](https://docs.zequenze.com/books/gate-api-reference/page/aaa-profile-M6Z) |
| `GET` | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_read" target="_blank">`/aaa_profile/{id}/`</a> | [Aaa Profile](https://docs.zequenze.com/books/gate-api-reference/page/aaa-profile-M6Z) |
| `PUT` | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_update" target="_blank">`/aaa_profile/{id}/`</a> | [Aaa Profile](https://docs.zequenze.com/books/gate-api-reference/page/aaa-profile-M6Z) |
| `PATCH` | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_partial_update" target="_blank">`/aaa_profile/{id}/`</a> | [Aaa Profile](https://docs.zequenze.com/books/gate-api-reference/page/aaa-profile-M6Z) |
| `DELETE` | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_delete" target="_blank">`/aaa_profile/{id}/`</a> | [Aaa Profile](https://docs.zequenze.com/books/gate-api-reference/page/aaa-profile-M6Z) |
| `GET` | <a href="https://gate.zequenze.com/api#/device_app_access_devices/device_app_access_devices_list" target="_blank">`/device_app_access_devices/`</a> | [Device App Access Devices](https://docs.zequenze.com/books/gate-api-reference/page/device-app-access-devices-HDH) |
| `GET` | <a href="https://gate.zequenze.com/api#/device_app_access_points/device_app_access_points_list" target="_blank">`/device_app_access_points/`</a> | [Device App Access Points](https://docs.zequenze.com/books/gate-api-reference/page/device-app-access-points-5ss) |
| `POST` | <a href="https://gate.zequenze.com/api#/device_app_connection_log/device_app_connection_log_create" target="_blank">`/device_app_connection_log/`</a> | [Device App Connection Log](https://docs.zequenze.com/books/gate-api-reference/page/device-app-connection-log-7uS) |
| `GET` | <a href="https://gate.zequenze.com/api#/device_app_connection_summary/device_app_connection_summary_list" target="_blank">`/device_app_connection_summary/`</a> | [Device App Connection Summary](https://docs.zequenze.com/books/gate-api-reference/page/device-app-connection-summary-i4D) |
| `GET` | <a href="https://gate.zequenze.com/api#/device_app_locations/device_app_locations_list" target="_blank">`/device_app_locations/`</a> | [Device App Locations](https://docs.zequenze.com/books/gate-api-reference/page/device-app-locations-x39) |
| `POST` | <a href="https://gate.zequenze.com/api#/device_app_register/device_app_register_create" target="_blank">`/device_app_register/`</a> | [Device App Register](https://docs.zequenze.com/books/gate-api-reference/page/device-app-register-MLh) |
| `POST` | <a href="https://gate.zequenze.com/api#/device_app_test_report/device_app_test_report_create" target="_blank">`/device_app_test_report/`</a> | [Device App Test Report](https://docs.zequenze.com/books/gate-api-reference/page/device-app-test-report-0Bv) |
| `POST` | <a href="https://gate.zequenze.com/api#/device_app_user_authenticate/device_app_user_authenticate_create" target="_blank">`/device_app_user_authenticate/`</a> | [Device App User Authenticate](https://docs.zequenze.com/books/gate-api-reference/page/device-app-user-authenticate-dUz) |
| `POST` | <a href="https://gate.zequenze.com/api#/device_app_user_update/device_app_user_update_create" target="_blank">`/device_app_user_update/`</a> | [Device App User Update](https://docs.zequenze.com/books/gate-api-reference/page/device-app-user-update-l1W) |
| `GET` | <a href="https://gate.zequenze.com/api#/hostspot_access_points/hostspot_access_points_list" target="_blank">`/hostspot_access_points/`</a> | [Hostspot Access Points](https://docs.zequenze.com/books/gate-api-reference/page/hostspot-access-points-h87) |
| `GET` | <a href="https://gate.zequenze.com/api#/hostspot_locations/hostspot_locations_list" target="_blank">`/hostspot_locations/`</a> | [Hostspot Locations](https://docs.zequenze.com/books/gate-api-reference/page/hostspot-locations-4pw) |
| `GET` | <a href="https://gate.zequenze.com/api#/me/me_organization_list" target="_blank">`/me/organization/`</a> | [Me](https://docs.zequenze.com/books/gate-api-reference/page/me-Vp5) |
| `GET` | <a href="https://gate.zequenze.com/api#/organization/organization_list" target="_blank">`/organization/`</a> | [Organization](https://docs.zequenze.com/books/gate-api-reference/page/organization-OMu) |
| `POST` | <a href="https://gate.zequenze.com/api#/portal_login/portal_login_create" target="_blank">`/portal_login/`</a> | [Portal Login](https://docs.zequenze.com/books/gate-api-reference/page/portal-login-KoR) |
| `GET` | <a href="https://gate.zequenze.com/api#/txlog_portal/txlog_portal_list" target="_blank">`/txlog_portal/`</a> | [Txlog Portal](https://docs.zequenze.com/books/gate-api-reference/page/txlog-portal-8Yf) |
| `GET` | <a href="https://gate.zequenze.com/api#/user/user_list" target="_blank">`/user/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `POST` | <a href="https://gate.zequenze.com/api#/user/user_create" target="_blank">`/user/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `GET` | <a href="https://gate.zequenze.com/api#/user/user_username_read" target="_blank">`/user/username/{username}/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `PUT` | <a href="https://gate.zequenze.com/api#/user/user_username_update" target="_blank">`/user/username/{username}/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `PATCH` | <a href="https://gate.zequenze.com/api#/user/user_username_partial_update" target="_blank">`/user/username/{username}/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `DELETE` | <a href="https://gate.zequenze.com/api#/user/user_username_delete" target="_blank">`/user/username/{username}/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `GET` | <a href="https://gate.zequenze.com/api#/user/user_read" target="_blank">`/user/{id}/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `PUT` | <a href="https://gate.zequenze.com/api#/user/user_update" target="_blank">`/user/{id}/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `PATCH` | <a href="https://gate.zequenze.com/api#/user/user_partial_update" target="_blank">`/user/{id}/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `DELETE` | <a href="https://gate.zequenze.com/api#/user/user_delete" target="_blank">`/user/{id}/`</a> | [User](https://docs.zequenze.com/books/gate-api-reference/page/user-j1q) |
| `GET` | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_list" target="_blank">`/user_extra/`</a> | [User Extra](https://docs.zequenze.com/books/gate-api-reference/page/user-extra-Bk0) |
| `POST` | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_create" target="_blank">`/user_extra/`</a> | [User Extra](https://docs.zequenze.com/books/gate-api-reference/page/user-extra-Bk0) |
| `GET` | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_read" target="_blank">`/user_extra/{id}/`</a> | [User Extra](https://docs.zequenze.com/books/gate-api-reference/page/user-extra-Bk0) |
| `PUT` | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_update" target="_blank">`/user_extra/{id}/`</a> | [User Extra](https://docs.zequenze.com/books/gate-api-reference/page/user-extra-Bk0) |
| `PATCH` | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_partial_update" target="_blank">`/user_extra/{id}/`</a> | [User Extra](https://docs.zequenze.com/books/gate-api-reference/page/user-extra-Bk0) |
| `DELETE` | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_delete" target="_blank">`/user_extra/{id}/`</a> | [User Extra](https://docs.zequenze.com/books/gate-api-reference/page/user-extra-Bk0) |
| `GET` | <a href="https://gate.zequenze.com/api#/user_token/user_token_list" target="_blank">`/user_token/`</a> | [User Token](https://docs.zequenze.com/books/gate-api-reference/page/user-token-7jF) |
| `POST` | <a href="https://gate.zequenze.com/api#/user_token/user_token_create" target="_blank">`/user_token/`</a> | [User Token](https://docs.zequenze.com/books/gate-api-reference/page/user-token-7jF) |
| `GET` | <a href="https://gate.zequenze.com/api#/user_token/user_token_read" target="_blank">`/user_token/{id}/`</a> | [User Token](https://docs.zequenze.com/books/gate-api-reference/page/user-token-7jF) |
| `PUT` | <a href="https://gate.zequenze.com/api#/user_token/user_token_update" target="_blank">`/user_token/{id}/`</a> | [User Token](https://docs.zequenze.com/books/gate-api-reference/page/user-token-7jF) |
| `PATCH` | <a href="https://gate.zequenze.com/api#/user_token/user_token_partial_update" target="_blank">`/user_token/{id}/`</a> | [User Token](https://docs.zequenze.com/books/gate-api-reference/page/user-token-7jF) |
| `DELETE` | <a href="https://gate.zequenze.com/api#/user_token/user_token_delete" target="_blank">`/user_token/{id}/`</a> | [User Token](https://docs.zequenze.com/books/gate-api-reference/page/user-token-7jF) |

---

## Quick Start

### 1. Authentication
Obtain your API token from the portal and include it in all requests.

### 2. Make a Request
```bash
curl -X GET "https://gate.zequenze.com/api/v1/endpoint/" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json"
```

### 3. Handle the Response
All responses are in JSON format. List endpoints include pagination.

---

## Response Codes

| Code | Status | Description |
|:----:|--------|-------------|
| 200 | OK | Request successful |
| 201 | Created | Resource created successfully |
| 204 | No Content | Request successful (DELETE operations) |
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Missing or invalid authentication token |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 500 | Server Error | Internal server error |

---

## Pagination

List endpoints return paginated results:

```json
{
  "count": 150,
  "next": "https://api.example.com/endpoint/?offset=50",
  "previous": null,
  "results": [...]
}
```

Use `limit` and `offset` query parameters to navigate through results.

# AAA Accounting

> The AAA Accounting endpoints provide access to authentication, authorization, and accounting transaction records from network access points. These endpoints allow you to retrieve detailed session information including user connections, data usage, session duration, and network access patterns for monitoring, reporting, and compliance purposes.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The AAA Accounting API category provides comprehensive access to network accounting records that track user sessions, data usage, and connection details across your network infrastructure. These endpoints are essential for:

- **Network Monitoring**: Track active and historical user sessions across access points
- **Usage Analytics**: Monitor data consumption patterns and session durations
- **Compliance Reporting**: Generate detailed reports for regulatory requirements
- **Billing Integration**: Access session data for usage-based billing systems
- **Security Auditing**: Review connection logs and identify anomalous network activity

The accounting records follow the RADIUS accounting standard, capturing detailed information about user sessions including start/stop times, data transfer volumes, client devices, and termination reasons. This data is automatically collected from network access points and made available through these read-only endpoints.

Key concepts:
- **Session Records**: Each record represents a user's network session with comprehensive connection details
- **Real-time Data**: Access both active sessions and historical records with flexible filtering
- **Multi-dimensional Filtering**: Filter by user, location, access point, time ranges, and session status
- **Pagination Support**: Efficiently handle large datasets with cursor-based pagination

---

## Endpoints

### GET /aaa_accounting/

**Description:** Retrieves a paginated list of AAA accounting records with flexible filtering options. This endpoint is your primary tool for accessing session data, whether you need to monitor active sessions, analyze historical usage patterns, or generate compliance reports. The response includes comprehensive session details from RADIUS accounting data.

**Use Cases:**
- Monitor current active user sessions across all access points
- Generate usage reports for specific time periods or locations
- Track data consumption patterns for capacity planning
- Export session data for external billing or analytics systems
- Audit network access for security compliance

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_accounting/?start_date=2024-01-01&end_date=2024-01-31&session_status=active&limit=50
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| start_date | string | query | No | Filter records from this date/time. Accepts ISO format: 2000-01-01, 2000-01-01 00:01:00, or 2000-01-01 00:01:00+00:00 |
| end_date | string | query | No | Filter records until this date/time. Accepts ISO format: 2000-01-01, 2000-01-01 00:01:00, or 2000-01-01 00:01:00+00:00 |
| user | integer | query | No | Filter records by specific user ID to see sessions for a particular user |
| access_point | integer | query | No | Filter records by access point ID to see sessions from specific hardware |
| location | integer | query | No | Filter records by location ID to see sessions from specific sites or buildings |
| client | integer | query | No | Filter records by client organization ID for multi-tenant environments |
| session_status | string | query | No | Filter by session state. Values: all (default), active (ongoing sessions), inactive (completed sessions) |
| cursor | string | query | No | Pagination cursor for retrieving the next page of results |
| limit | integer | query | No | Number of records per page (default varies, recommended: 10-100) |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/aaa_accounting/?start_date=2024-01-01&session_status=active&limit=25" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "next": "https://gate.zequenze.com/api/v1/aaa_accounting/?cursor=xyz123&limit=25",
  "previous": null,
  "results": [
    {
      "radacctid": 12345,
      "acctsessionid": "sess_abc123",
      "acctuniqueid": "unique_456def",
      "username": "john.doe@company.com",
      "groupname": "employees",
      "realm": "company.com",
      "nasipaddress": "192.168.1.10",
      "nasportid": "wifi0",
      "nasporttype": "Wireless-802.11",
      "acctstarttime": "2024-01-15T09:30:00Z",
      "acctupdatetime": "2024-01-15T10:15:00Z",
      "acctstoptime": null,
      "acctinterval": 600,
      "acctsessiontime": 2700,
      "acctauthentic": "RADIUS",
      "connectinfo_start": "CONNECT 54Mbps 802.11n",
      "connectinfo_stop": null,
      "acctinputoctets": 15728640,
      "acctoutputoctets": 52428800,
      "calledstationid": "00:1A:2B:3C:4D:5E",
      "callingstationid": "AA:BB:CC:DD:EE:FF",
      "acctterminatecause": null,
      "servicetype": "Framed-User",
      "framedprotocol": "PPP",
      "framedipaddress": "10.0.1.45",
      "organization_id": "org_789",
      "user_id": "user_456",
      "user_transaction_id": "txn_321",
      "client_id": "client_123",
      "client_short_name": "HQ-Office",
      "location_id": "loc_987",
      "access_point_id": "ap_654",
      "access_point_name": "AP-Floor2-East",
      "location_name": "Headquarters Building",
      "nasidentifier": "ap-hq-f2e-01",
      "klass": "premium",
      "access_point_mac_addr": "00:1A:2B:3C:4D:5E",
      "ssid": "CorpWiFi-Secure"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated accounting records |
| 401 | Unauthorized - Invalid or missing API token |
| 400 | Bad Request - Invalid date format or parameter values |

---

### GET /aaa_accounting/{radacctid}/

**Description:** Retrieves detailed information for a specific AAA accounting record by its unique radacctid. This endpoint provides complete session details for individual accounting transactions, useful for detailed analysis, troubleshooting specific user issues, or generating detailed session reports.

**Use Cases:**
- Investigate specific user connection issues or session problems
- Retrieve complete session details for billing or audit purposes
- Analyze detailed connection parameters for network optimization
- Export individual session records for compliance documentation

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_accounting/12345/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| radacctid | integer | path | Yes | The unique accounting record ID to retrieve |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/aaa_accounting/12345/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "radacctid": 12345,
  "acctsessionid": "sess_abc123",
  "acctuniqueid": "unique_456def",
  "username": "jane.smith@company.com",
  "groupname": "managers",
  "realm": "company.com",
  "nasipaddress": "192.168.1.15",
  "nasportid": "wifi1",
  "nasporttype": "Wireless-802.11",
  "acctstarttime": "2024-01-15T14:20:00Z",
  "acctupdatetime": "2024-01-15T16:45:00Z",
  "acctstoptime": "2024-01-15T17:30:00Z",
  "acctinterval": 300,
  "acctsessiontime": 11400,
  "acctauthentic": "RADIUS",
  "connectinfo_start": "CONNECT 300Mbps 802.11ac",
  "connectinfo_stop": "User-Request",
  "acctinputoctets": 234567890,
  "acctoutputoctets": 876543210,
  "calledstationid": "00:1A:2B:3C:4D:5F",
  "callingstationid": "BB:CC:DD:EE:FF:AA",
  "acctterminatecause": "User-Request",
  "servicetype": "Framed-User",
  "framedprotocol": "PPP",
  "framedipaddress": "10.0.1.78",
  "organization_id": "org_789",
  "user_id": "user_789",
  "user_transaction_id": "txn_456",
  "client_id": "client_123",
  "client_short_name": "HQ-Office",
  "location_id": "loc_987",
  "access_point_id": "ap_655",
  "access_point_name": "AP-Floor3-West",
  "location_name": "Headquarters Building",
  "nasidentifier": "ap-hq-f3w-02",
  "klass": "standard",
  "access_point_mac_addr": "00:1A:2B:3C:4D:5F",
  "ssid": "CorpWiFi-Guest"
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns the specific accounting record |
| 401 | Unauthorized - Invalid or missing API token |
| 404 | Not Found - Accounting record with specified ID does not exist |

---

## Common Use Cases

### Use Case 1: Active Session Monitoring Dashboard
Retrieve all currently active sessions to display real-time network usage. Use the session_status=active filter to show only ongoing connections, perfect for network operations centers or IT dashboards.

### Use Case 2: Monthly Usage Reporting
Generate monthly reports by filtering with start_date and end_date parameters. Combine with location or access_point filters to create detailed usage reports for specific sites or network segments.

### Use Case 3: User Behavior Analysis
Track specific user patterns by filtering with the user parameter, then analyze session durations, data usage, and connection frequency to optimize network resources or identify training needs.

### Use Case 4: Billing Data Export
Extract session data for usage-based billing by querying records within billing periods and calculating total session time and data transfer volumes per user or organization.

### Use Case 5: Security Incident Investigation
When investigating security incidents, use the specific record endpoint to get complete session details including IP addresses, MAC addresses, connection times, and termination causes for forensic analysis.

---

## Best Practices

- **Use Date Filters Effectively**: Always use start_date and end_date parameters when querying historical data to improve performance and reduce response times
- **Implement Proper Pagination**: Use the cursor-based pagination for large datasets rather than trying to retrieve all records at once
- **Cache Responses**: Accounting data is generally immutable once sessions complete, making it suitable for caching to reduce API calls
- **Monitor Rate Limits**: Be mindful of API rate limits when building automated reporting systems or real-time dashboards
- **Handle Timezones**: All timestamps are in UTC; convert to local timezone in your application as needed
- **Filter by Organization**: In multi-tenant environments, always filter by client parameter to ensure proper data isolation
- **Use Session Status Appropriately**: Filter by session_status=active for monitoring dashboards, and session_status=inactive for historical reporting
- **Error Handling**: Implement retry logic for network timeouts and handle 404 responses gracefully when querying specific record IDs

---

# AAA Profile

> The AAA Profile API endpoints provide comprehensive management of Authentication, Authorization, and Accounting (AAA) profiles for network access control. These endpoints allow you to create, configure, and manage RADIUS-style attribute profiles that define user access policies, network permissions, and accounting rules for network devices and services.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The AAA Profile API enables network administrators to manage authentication and authorization profiles that control network access for users and devices. AAA profiles contain sets of RADIUS attributes that define what resources users can access, how they authenticate, and what accounting information is collected.

**Key Concepts:**

- **Reply Attributes**: Sent back to the Network Access Server (NAS) during successful authentication, defining user permissions and access parameters
- **Check Attributes**: Used during authentication to validate user credentials and access rights
- **Operators**: Define how attributes are processed (=, +=, :=, ==, !=, >, >=, <, <=, =*, !*)

**Common Use Cases:**

- Creating user access policies for different user groups (employees, guests, contractors)
- Defining VLAN assignments and bandwidth limits
- Setting session timeouts and access restrictions
- Managing VPN access profiles
- Configuring wireless network access policies

The API supports full CRUD operations, allowing you to list, create, retrieve, update, and delete AAA profiles with comprehensive attribute management.

---

## Endpoints

### GET /aaa_profile/

**Description:** Retrieves a paginated list of all AAA profiles in your organization. This endpoint is essential for discovering existing profiles, monitoring configuration changes, and implementing profile management interfaces.

**Use Cases:**
- Building administrative dashboards that display all configured access policies
- Auditing network access configurations across your organization
- Synchronizing AAA profiles with external configuration management systems

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/?limit=20&offset=0
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| limit | integer | query | No | Number of results to return per page (default: 20, max: 100) |
| offset | integer | query | No | Starting position for pagination (default: 0) |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/aaa_profile/?limit=10&offset=0" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 25,
  "next": "https://gate.zequenze.com/api/v1/aaa_profile/?limit=10&offset=10",
  "previous": null,
  "results": [
    {
      "id": 1,
      "name": "Employee Access Profile",
      "short_name": "employee-access",
      "description": "Standard access profile for full-time employees",
      "organization_id": "org_12345",
      "reply_attribute": [
        {
          "attribute": "Tunnel-Type",
          "op": ":=",
          "value": "VLAN"
        },
        {
          "attribute": "Tunnel-Medium-Type",
          "op": ":=",
          "value": "IEEE-802"
        }
      ],
      "check_attribute": [
        {
          "attribute": "User-Password",
          "op": "==",
          "value": "%{User-Password}"
        }
      ]
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated list of AAA profiles |
| 401 | Unauthorized - Invalid or missing authentication token |
| 403 | Forbidden - Insufficient permissions to access profiles |

---

### POST /aaa_profile/

**Description:** Creates a new AAA profile with specified reply and check attributes. This endpoint allows you to define new access policies and authentication rules that can be applied to users and network devices.

**Use Cases:**
- Setting up access policies for new user groups or departments
- Creating specialized profiles for guest network access
- Defining contractor or temporary user access restrictions

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/
```

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/aaa_profile/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Guest WiFi Profile",
    "short_name": "guest-wifi",
    "description": "Limited access profile for guest users",
    "reply_attribute": [
      {
        "attribute": "Session-Timeout",
        "op": ":=",
        "value": "3600"
      },
      {
        "attribute": "Tunnel-Private-Group-Id",
        "op": ":=",
        "value": "100"
      }
    ],
    "check_attribute": [
      {
        "attribute": "Calling-Station-Id",
        "op": "=*",
        "value": "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"
      }
    ]
  }'
```

**Request Body Example:**
```json
{
  "name": "VPN Access Profile",
  "short_name": "vpn-access",
  "description": "Profile for remote VPN users with bandwidth limits",
  "reply_attribute": [
    {
      "attribute": "Framed-IP-Address",
      "op": ":=",
      "value": "255.255.255.254"
    },
    {
      "attribute": "Acct-Interim-Interval",
      "op": ":=",
      "value": "600"
    }
  ],
  "check_attribute": [
    {
      "attribute": "NAS-Port-Type",
      "op": "==",
      "value": "Virtual"
    }
  ]
}
```

**Example Response:**
```json
{
  "id": 15,
  "name": "VPN Access Profile",
  "short_name": "vpn-access",
  "description": "Profile for remote VPN users with bandwidth limits",
  "organization_id": "org_12345",
  "reply_attribute": [
    {
      "attribute": "Framed-IP-Address",
      "op": ":=",
      "value": "255.255.255.254"
    },
    {
      "attribute": "Acct-Interim-Interval",
      "op": ":=",
      "value": "600"
    }
  ],
  "check_attribute": [
    {
      "attribute": "NAS-Port-Type",
      "op": "==",
      "value": "Virtual"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - AAA profile successfully created |
| 400 | Bad Request - Invalid data in request body |
| 401 | Unauthorized - Invalid or missing authentication token |
| 409 | Conflict - Profile with same short_name already exists |

---

### GET /aaa_profile/{id}/

**Description:** Retrieves detailed information about a specific AAA profile by its ID. This endpoint provides complete profile configuration including all reply and check attributes with their operators and values.

**Use Cases:**
- Reviewing specific profile configurations before making changes
- Debugging authentication issues by examining profile attributes
- Exporting profile configurations for backup or migration

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/15/
```

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/aaa_profile/15/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "id": 15,
  "name": "Manager Access Profile",
  "short_name": "manager-access",
  "description": "Enhanced access profile for management staff with extended permissions",
  "organization_id": "org_12345",
  "reply_attribute": [
    {
      "attribute": "Filter-Id",
      "op": ":=",
      "value": "manager_acl"
    },
    {
      "attribute": "Session-Timeout",
      "op": ":=",
      "value": "28800"
    },
    {
      "attribute": "Tunnel-Private-Group-Id",
      "op": ":=",
      "value": "200"
    }
  ],
  "check_attribute": [
    {
      "attribute": "User-Password",
      "op": "==",
      "value": "%{User-Password}"
    },
    {
      "attribute": "Huntgroup-Name",
      "op": "==",
      "value": "management"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns the specified AAA profile |
| 401 | Unauthorized - Invalid or missing authentication token |
| 404 | Not Found - AAA profile with specified ID does not exist |

---

### PUT /aaa_profile/{id}/

**Description:** Completely replaces an existing AAA profile with new configuration data. This endpoint performs a full update, replacing all profile attributes with the provided values.

**Use Cases:**
- Implementing major policy changes that affect multiple attributes
- Standardizing profiles across different environments
- Migrating from legacy configurations to new attribute sets

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/15/
```

**cURL Example:**
```bash
curl -X PUT "https://gate.zequenze.com/api/v1/aaa_profile/15/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Updated Manager Profile",
    "short_name": "manager-access-v2",
    "description": "Revised manager access with new security policies",
    "reply_attribute": [
      {
        "attribute": "Filter-Id",
        "op": ":=",
        "value": "manager_acl_v2"
      },
      {
        "attribute": "Session-Timeout",
        "op": ":=",
        "value": "14400"
      }
    ],
    "check_attribute": [
      {
        "attribute": "User-Password",
        "op": "==",
        "value": "%{User-Password}"
      }
    ]
  }'
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - AAA profile successfully updated |
| 400 | Bad Request - Invalid data in request body |
| 401 | Unauthorized - Invalid or missing authentication token |
| 404 | Not Found - AAA profile with specified ID does not exist |

---

### PATCH /aaa_profile/{id}/

**Description:** Partially updates an existing AAA profile, modifying only the specified fields while preserving existing configuration for unspecified attributes. This endpoint is ideal for making targeted changes without affecting the entire profile.

**Use Cases:**
- Adjusting session timeouts or bandwidth limits without changing access rules
- Adding new reply attributes while keeping existing check attributes
- Making quick configuration changes for specific requirements

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/15/
```

**cURL Example:**
```bash
curl -X PATCH "https://gate.zequenze.com/api/v1/aaa_profile/15/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "description": "Updated description with new security requirements",
    "reply_attribute": [
      {
        "attribute": "Session-Timeout",
        "op": ":=",
        "value": "21600"
      }
    ]
  }'
```

**Example Response:**
```json
{
  "id": 15,
  "name": "Manager Access Profile",
  "short_name": "manager-access",
  "description": "Updated description with new security requirements",
  "organization_id": "org_12345",
  "reply_attribute": [
    {
      "attribute": "Session-Timeout",
      "op": ":=",
      "value": "21600"
    }
  ],
  "check_attribute": [
    {
      "attribute": "User-Password",
      "op": "==",
      "value": "%{User-Password}"
    },
    {
      "attribute": "Huntgroup-Name",
      "op": "==",
      "value": "management"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - AAA profile successfully updated |
| 400 | Bad Request - Invalid data in request body |
| 401 | Unauthorized - Invalid or missing authentication token |
| 404 | Not Found - AAA profile with specified ID does not exist |

---

### DELETE /aaa_profile/{id}/

**Description:** Permanently removes an AAA profile from the system. This action cannot be undone and will affect any users or devices currently assigned to this profile.

**Use Cases:**
- Removing obsolete profiles that are no longer needed
- Cleaning up test or temporary configurations
- Decommissioning access policies for discontinued services

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/15/
```

**cURL Example:**
```bash
curl -X DELETE "https://gate.zequenze.com/api/v1/aaa_profile/15/" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 204 | No Content - AAA profile successfully deleted |
| 401 | Unauthorized - Invalid or missing authentication token |
| 404 | Not Found - AAA profile with specified ID does not exist |
| 409 | Conflict - Profile is in use and cannot be deleted |

---

## Common Use Cases

### Use Case 1: Employee Onboarding
Create standardized access profiles for new employees by using POST /aaa_profile/ with appropriate VLAN assignments and session timeouts, then retrieve the profile using GET /aaa_profile/{id}/ to verify configuration.

### Use Case 2: Guest Network Management
Set up time-limited guest access by creating profiles with Session-Timeout attributes and bandwidth restrictions, using the reply_attribute array to define access parameters.

### Use Case 3: Profile Maintenance
Regularly audit existing profiles using GET /aaa_profile/ with pagination, then use PATCH operations to update specific attributes like session timeouts or access rules without disrupting other configuration.

### Use Case 4: Security Policy Updates
Implement organization-wide security changes by retrieving all profiles with GET /aaa_profile/, then using PUT operations to update profiles with new check attributes for enhanced authentication requirements.

### Use Case 5: Seasonal Access Control
Create and delete temporary profiles for contractors or seasonal workers using POST and DELETE operations, with specific reply attributes that limit access duration and network resources.

---

## Best Practices

- **Attribute Operators**: Use `:=` for setting values, `==` for exact matches in checks, and `=*` for pattern matching with regular expressions
- **Profile Naming**: Use descriptive names and consistent slug-format short_names to make profiles easily identifiable
- **Pagination**: When listing profiles, use appropriate limit values (20-50) to balance performance and usability
- **Error Handling**: Always check for 409 conflicts when creating profiles, as short_name values must be unique within an organization
- **Testing**: Create test profiles in non-production environments first, as deleted profiles cannot be recovered
- **Documentation**: Maintain detailed descriptions for complex profiles to help other administrators understand their purpose and configuration

---

# Device App Access Devices

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/device_app_access_devices/`](#get-device_app_access_devices) | <a href="https://gate.zequenze.com/api#/device_app_access_devices/device_app_access_devices_list" target="_blank">Swagger ↗</a> |

---
> The Device App Access Devices API provides endpoints for managing and retrieving access point devices within the GATE system. This endpoint allows you to list and filter access control devices such as door controllers, card readers, and other physical access points used for building security and entry management.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Device App Access Devices API is designed for managing physical access control devices within your organization's security infrastructure. This API category focuses on access points - the hardware devices that control entry to buildings, rooms, or secure areas.

**Key Features:**
- Retrieve comprehensive lists of all access control devices
- Filter devices by their last modification date
- Access detailed device information including location data, status, and configuration
- Support for pagination to handle large device inventories
- Geographic information for device mapping and location services

**Common Integration Scenarios:**
- Building management systems that need to display all access points
- Security dashboards showing device status and locations
- Mobile applications for facility management
- Reporting systems that track device changes and maintenance
- Integration with mapping services using device coordinates

Access devices in the GATE system represent physical hardware like card readers, biometric scanners, door controllers, and gate mechanisms. Each device contains detailed location information, operational status, and organizational assignment data.

---

## Endpoints

<a id="get-device_app_access_devices"></a>

### GET /device_app_access_devices/

**Description:** Retrieves a paginated list of all access control devices in your organization. This endpoint provides comprehensive device information including location data, operational status, and device metadata. Use this endpoint to get an overview of your access control infrastructure or to synchronize device data with external systems.

**Use Cases:**
- Display all access points in a security management dashboard
- Synchronize device inventory with external facility management systems
- Generate reports on access control infrastructure
- Build device location maps using latitude/longitude coordinates
- Monitor device status and recent configuration changes

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/device_app_access_devices/?limit=50&offset=0&last_change__gte=2024-01-01T00:00:00Z
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| last_change__gte | string | query | No | Filter devices modified on or after this date (ISO 8601 format). Useful for incremental sync operations |
| limit | integer | query | No | Number of results to return per page (default: system defined, recommended: 50-100) |
| offset | integer | query | No | The initial index from which to return results (used for pagination) |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/device_app_access_devices/?limit=25&offset=0" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 156,
  "next": "https://gate.zequenze.com/api/v1/device_app_access_devices/?limit=25&offset=25",
  "previous": null,
  "results": [
    {
      "id": 1001,
      "name": "Main Entrance Card Reader",
      "short_name": "main-entrance-reader",
      "is_active": true,
      "description": "Primary access control device for building main entrance",
      "organization_id": "org-12345",
      "thumbnail": "https://gate.zequenze.com/media/devices/main-entrance-thumb.jpg",
      "address": "123 Corporate Blvd",
      "reference": "Building A - Main Entry",
      "city": "San Francisco",
      "postal_code": "94105",
      "state": "California",
      "region": "Northern California",
      "country_code": "US",
      "latitude": "37.7749",
      "longitude": "-122.4194",
      "created": "2024-01-15T10:30:00Z",
      "last_change": "2024-02-10T14:22:33Z"
    },
    {
      "id": 1002,
      "name": "Executive Floor Biometric Scanner",
      "short_name": "exec-floor-biometric",
      "is_active": true,
      "description": "High-security biometric access control for executive level",
      "organization_id": "org-12345",
      "thumbnail": "https://gate.zequenze.com/media/devices/biometric-scanner-thumb.jpg",
      "address": "123 Corporate Blvd",
      "reference": "Building A - Floor 15",
      "city": "San Francisco",
      "postal_code": "94105",
      "state": "California",
      "region": "Northern California",
      "country_code": "US",
      "latitude": "37.7749",
      "longitude": "-122.4194",
      "created": "2024-01-20T09:15:00Z",
      "last_change": "2024-02-08T11:45:22Z"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated list of access devices |
| 401 | Unauthorized - Invalid or missing Bearer token |
| 403 | Forbidden - Token valid but lacks permission to access devices |
| 500 | Internal Server Error - Contact support if persistent |

---

## Common Use Cases

### Use Case 1: Building Security Dashboard
Create a real-time dashboard showing all access control devices in your facilities. Use the base endpoint to retrieve all devices and display their status, locations, and recent activity. Filter by `last_change__gte` to highlight recently modified devices that may need attention.

### Use Case 2: Device Inventory Synchronization
Synchronize your access control device inventory with external facility management or maintenance systems. Use pagination with consistent `limit` values and track the `last_change` timestamps to perform incremental updates rather than full synchronization.

### Use Case 3: Interactive Facility Maps
Build interactive maps of your facilities showing access point locations. Use the `latitude` and `longitude` fields to plot device positions, with `thumbnail` images and `description` text for device details in map popups.

### Use Case 4: Maintenance and Compliance Reporting
Generate reports on access control infrastructure for compliance audits or maintenance scheduling. Filter devices by location (`city`, `state`, `country_code`) or use `last_change__gte` to identify devices that haven't been updated recently and may need inspection.

### Use Case 5: Mobile Facility Management App
Develop mobile applications for security personnel or facility managers. Use the API to show nearby access devices based on geographic coordinates, display device status, and provide quick access to device information and controls.

---

## Best Practices

- **Implement Pagination**: Always use `limit` and `offset` parameters when dealing with large device inventories. A limit of 50-100 devices per request provides good performance without overwhelming your application.

- **Use Incremental Updates**: Leverage the `last_change__gte` parameter to fetch only recently modified devices, reducing bandwidth and processing time for synchronization operations.

- **Cache Device Data**: Device information typically doesn't change frequently. Implement appropriate caching strategies with cache invalidation based on `last_change` timestamps.

- **Handle Geographic Data**: When using `latitude` and `longitude` coordinates, validate that both values are present before attempting to plot devices on maps, as some devices may not have location data.

- **Monitor Active Status**: Always check the `is_active` field when displaying devices to users. Inactive devices may be offline for maintenance or decommissioned.

- **Store Organization Context**: The `organization_id` field helps maintain proper data isolation in multi-tenant applications. Always verify device access permissions based on user organization membership.

# Device App Access Points

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/device_app_access_points/`](#get-device_app_access_points) | <a href="https://gate.zequenze.com/api#/device_app_access_points/device_app_access_points_list" target="_blank">Swagger ↗</a> |

---
> The Device App Access Points API provides endpoints for retrieving and managing access point locations within your organization's network infrastructure. This API enables you to query access points with filtering capabilities, manage location-based services, and integrate physical access point data into your applications for monitoring, reporting, and operational management.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Device App Access Points API category focuses on managing physical access points within your organization's infrastructure. Access points represent physical locations where users can connect to services, authenticate, or access resources - such as Wi-Fi access points, entry gates, kiosks, or service terminals.

This API enables you to:
- Retrieve comprehensive lists of access points with detailed location and configuration data
- Filter access points by modification dates to sync changes
- Access geographic and organizational information for each access point
- Integrate access point data into monitoring dashboards, mobile applications, or reporting systems

Access points contain rich metadata including geographic coordinates, organizational details, physical addresses, and operational status. This makes the API particularly valuable for facility management, network monitoring, user experience optimization, and compliance reporting scenarios.

The pagination system allows efficient handling of large access point inventories, while filtering capabilities enable incremental synchronization and targeted queries based on your specific operational requirements.

---

## Endpoints

<a id="get-device_app_access_points"></a>

### GET /device_app_access_points/

**Description:** Retrieves a paginated list of access points within your organization. This endpoint returns comprehensive information about each access point including location data, configuration details, and operational status. Use this endpoint to build access point inventories, create location-based services, or synchronize access point data with external systems.

**Use Cases:**
- Building a real-time dashboard showing all active access points across facilities
- Synchronizing access point data with external monitoring or management systems
- Creating mobile applications that help users locate nearby access points
- Generating compliance reports that include physical location and access point details
- Implementing location-based user authentication or service routing

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/device_app_access_points/?limit=25&offset=0&last_change__gte=2024-01-01T00:00:00Z
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| last_change__gte | string | query | No | Filter access points modified on or after this date/time (ISO 8601 format). Useful for incremental synchronization. |
| limit | integer | query | No | Number of results to return per page. Default and maximum values depend on server configuration. |
| offset | integer | query | No | The initial index from which to return results. Use with limit for pagination. |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/device_app_access_points/?limit=25&offset=0" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 156,
  "next": "https://gate.zequenze.com/api/v1/device_app_access_points/?limit=25&offset=25",
  "previous": null,
  "results": [
    {
      "id": 1001,
      "name": "Main Lobby WiFi Access Point",
      "short_name": "main-lobby-ap",
      "is_active": true,
      "description": "Primary wireless access point serving the main lobby and reception area",
      "organization_id": "org_12345",
      "thumbnail": "https://gate.zequenze.com/media/thumbnails/access_points/ap_1001.jpg",
      "address": "123 Corporate Boulevard",
      "reference": "Building A - Level 1 - Sector 3",
      "city": "San Francisco",
      "postal_code": "94105",
      "state": "California", 
      "region": "West Coast",
      "country_code": "US",
      "latitude": "37.7749",
      "longitude": "-122.4194",
      "created": "2024-01-15T09:30:00Z",
      "last_change": "2024-02-10T14:22:30Z"
    },
    {
      "id": 1002,
      "name": "Conference Room B Access Terminal",
      "short_name": "conf-room-b-terminal",
      "is_active": true,
      "description": "Secure access terminal for Conference Room B with integrated authentication",
      "organization_id": "org_12345",
      "thumbnail": "https://gate.zequenze.com/media/thumbnails/access_points/ap_1002.jpg",
      "address": "123 Corporate Boulevard",
      "reference": "Building A - Level 2 - Room B201",
      "city": "San Francisco",
      "postal_code": "94105",
      "state": "California",
      "region": "West Coast", 
      "country_code": "US",
      "latitude": "37.7751",
      "longitude": "-122.4192",
      "created": "2024-01-20T11:45:00Z",
      "last_change": "2024-02-08T16:15:45Z"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated access points data |
| 401 | Unauthorized - Invalid or missing Bearer token |
| 403 | Forbidden - Token valid but insufficient permissions for this organization |
| 404 | Not Found - Endpoint not available |
| 422 | Unprocessable Entity - Invalid query parameters (e.g., malformed date format) |

---

## Common Use Cases

### Use Case 1: Real-Time Access Point Monitoring Dashboard
Build a monitoring dashboard that displays all active access points with their current status, location, and last update times. Use pagination to efficiently load large numbers of access points and implement real-time updates by periodically querying with `last_change__gte` to fetch only recently modified access points.

### Use Case 2: Mobile App Location Services
Develop a mobile application that helps users find nearby access points. Retrieve all access points with geographic coordinates, then use the latitude/longitude data to calculate distances and display the closest available access points to the user's current location.

### Use Case 3: Incremental Data Synchronization
Synchronize access point data with external systems like network monitoring tools or facility management software. Use the `last_change__gte` parameter to fetch only access points that have been modified since your last synchronization, reducing bandwidth and processing overhead.

### Use Case 4: Compliance and Audit Reporting
Generate compliance reports that require detailed location and access point information. Retrieve comprehensive access point data including addresses, references, and organizational details to create audit trails and compliance documentation.

### Use Case 5: Geographic Access Point Distribution Analysis
Analyze the geographic distribution of access points across different regions, cities, or facilities. Use the location data (city, state, region, country_code) to group access points and generate insights about coverage areas and deployment patterns.

---

## Best Practices

- **Implement Pagination Efficiently**: Use reasonable limit values (25-100 items per page) to balance performance and user experience. Always check for the `next` field to determine if additional pages are available.

- **Use Incremental Synchronization**: When building systems that need to stay synchronized with access point data, use the `last_change__gte` parameter to fetch only recently modified records, reducing API calls and improving performance.

- **Handle Geographic Data Appropriately**: Latitude and longitude values are returned as strings in decimal format. Convert to appropriate numeric types in your application and validate coordinates before using them in mapping or distance calculations.

- **Cache Access Point Data**: Access point configurations typically don't change frequently. Implement appropriate caching strategies with cache invalidation based on `last_change` timestamps to reduce unnecessary API calls.

- **Monitor Rate Limits**: Implement proper error handling for rate limiting scenarios and consider implementing exponential backoff strategies for retrying failed requests.

- **Validate Country Codes**: The API supports a comprehensive list of ISO country codes including special territories and regions. Ensure your application can handle the full range of possible country_code values when implementing location-based features.

---

# Device App Connection Log

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `POST` | [`/device_app_connection_log/`](#post-device_app_connection_log) | <a href="https://gate.zequenze.com/api#/device_app_connection_log/device_app_connection_log_create" target="_blank">Swagger ↗</a> |

---
> The Device App Connection Log API enables applications to register and track network connection details from devices. This endpoint is essential for monitoring network usage patterns, connection quality metrics, and geographic location data across different network types including WiFi, Mobile, Bluetooth, and Ethernet connections.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Device App Connection Log API provides a centralized way to collect and store detailed network connection information from devices across your organization. This API is particularly valuable for:

- **Network Analytics**: Track connection patterns, network performance, and usage statistics across different locations and network types
- **Quality Monitoring**: Collect signal strength, link speed, and connection quality metrics to identify network issues
- **Geographic Tracking**: Monitor device connectivity across different locations using latitude/longitude data
- **Security Analysis**: Track network security types and authentication methods to ensure compliance with security policies
- **Roaming Detection**: Identify when devices are operating outside their home networks

The connection logs capture comprehensive network details including network identification (BSSID, Cell ID, MCC/MNC), performance metrics (RSSI, SINR, link speed), data usage (inbound/outbound bytes), and location information. This data is essential for network administrators, IT teams, and developers building location-aware or network-dependent applications.

---

## Endpoints

<a id="post-device_app_connection_log"></a>

### POST /device_app_connection_log/

**Description:** Registers a comprehensive network connection log entry with detailed network characteristics, performance metrics, and location data. This endpoint accepts connection data from various network types and stores it for analytics and monitoring purposes.

**Use Cases:**
- Mobile applications reporting network connectivity status and performance
- IoT devices logging connection quality for network optimization
- Enterprise applications tracking employee device connectivity across locations
- Network monitoring tools collecting performance data from field devices

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/device_app_connection_log/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| data | string | body | Yes | JSON string containing the network connection log data |

**Request Body Schema:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| network_name | string | No | Name of the current network (e.g., "Office WiFi", "Guest Network") |
| network_type | string | Yes | Network type: 'wi' (WiFi), 'mo' (Mobile), 'bl' (Bluetooth), 'et' (Ethernet) |
| network_security | string | Yes | Security type: 'opn' (Open), 'wep' (WEP), 'wpa' (WPA), 'wp2' (WPA2), '3gp' (3GPP) |
| network_mccmnc | string | No | Mobile network MCC/MNC code (e.g., "31026" for T-Mobile US) |
| frequency | number | No | Wireless network frequency in GHz (e.g., 2.4, 5.0) |
| authentication | string | No | Authentication method: 'non', 'cpo' (Captive portal), 'wis' (WISPr), 'psk', 'rad' (RADIUS), 'eap', '3gp' |
| bssid | string | No | Wireless network BSSID (MAC address of access point) |
| cellid | string | No | Mobile network Cell ID for cellular connections |
| roaming | boolean | No | Whether device is roaming outside its home network |
| latitude | string | No | Device latitude in decimal format |
| longitude | string | No | Device longitude in decimal format |
| inbytes | integer | No | Bytes received during this connection session |
| outbytes | integer | No | Bytes transmitted during this connection session |
| link_speed | number | No | Connection speed in Mbps as reported by network adapter |
| quality_metric | string | No | Quality measurement type: 'rssi' (RSSI) or 'sinr' (SINR) |
| quality_value | number | No | Signal quality value corresponding to the metric type |

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/device_app_connection_log/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_name": "Office WiFi Main",
    "network_type": "wi",
    "network_security": "wp2",
    "frequency": 5.0,
    "authentication": "eap",
    "bssid": "00:1a:2b:3c:4d:5e",
    "roaming": false,
    "latitude": "40.7128",
    "longitude": "-74.0060",
    "inbytes": 1048576,
    "outbytes": 524288,
    "link_speed": 150.0,
    "quality_metric": "rssi",
    "quality_value": -45
  }'
```

**Example Response:**
```json
{
  "network_name": "Office WiFi Main",
  "network_type": "wi",
  "network_security": "wp2",
  "network_mccmnc": null,
  "frequency": 5.0,
  "authentication": "eap",
  "bssid": "00:1a:2b:3c:4d:5e",
  "cellid": null,
  "roaming": false,
  "latitude": "40.7128",
  "longitude": "-74.0060",
  "inbytes": 1048576,
  "outbytes": 524288,
  "link_speed": 150.0,
  "quality_metric": "rssi",
  "quality_value": -45.0
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - Connection log successfully registered |
| 400 | Bad Request - Invalid data format or missing required fields |
| 401 | Unauthorized - Invalid or missing authentication token |
| 422 | Unprocessable Entity - Data validation failed |

---

## Common Use Cases

### Use Case 1: Mobile App Network Monitoring
Mobile applications can use this endpoint to track network performance and connectivity patterns. When users experience connectivity issues, the app can log detailed network information including signal strength, network type, and location data to help identify problematic areas or network configurations.

### Use Case 2: IoT Device Fleet Management
IoT devices deployed across multiple locations can regularly report their connectivity status, helping administrators monitor network coverage, identify devices experiencing poor connectivity, and optimize network infrastructure based on actual usage patterns and performance metrics.

### Use Case 3: Enterprise Security Compliance
Organizations can track which networks their devices connect to, monitor security protocols in use, and ensure devices only connect to approved networks. This is particularly valuable for detecting unauthorized network access or identifying devices connecting to unsecured networks.

### Use Case 4: Network Performance Analytics
Network administrators can collect aggregated connection data to analyze network performance trends, identify peak usage times, monitor data consumption patterns, and make informed decisions about network capacity and infrastructure improvements.

### Use Case 5: Location-Based Services
Applications providing location-based services can correlate network connectivity data with geographic coordinates to understand connectivity patterns across different locations, optimize content delivery, and provide location-aware features based on network availability.

---

## Best Practices

- **Data Validation**: Always validate network type and security values against the allowed enumeration before sending requests. Invalid values will result in validation errors.

- **Privacy Considerations**: When collecting location data (latitude/longitude), ensure compliance with privacy regulations and obtain appropriate user consent. Consider data anonymization for analytics purposes.

- **Batch Processing**: For applications generating high volumes of connection logs, consider implementing local queuing and batch processing to reduce API call frequency and improve performance.

- **Error Handling**: Implement robust error handling for network connectivity issues. Store logs locally when the API is unreachable and sync when connectivity is restored.

- **Data Completeness**: While many fields are optional, providing comprehensive data improves the value of analytics. Include quality metrics, data usage, and location information when available.

- **Security**: Never log sensitive authentication credentials or personal information. The API is designed to capture network characteristics, not user credentials or private data.

- **Rate Limiting**: Implement appropriate rate limiting in your applications to avoid overwhelming the API, especially for devices that frequently change networks or generate high-frequency connection events.

---

# Device App Connection Summary

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/device_app_connection_summary/`](#get-device_app_connection_summary) | <a href="https://gate.zequenze.com/api#/device_app_connection_summary/device_app_connection_summary_list" target="_blank">Swagger ↗</a> |

---
> The Device App Connection Summary API provides insights into how devices connect to applications within your system. This endpoint delivers aggregated connection data, helping administrators monitor device usage patterns, track application connectivity, and generate reports for network optimization and troubleshooting.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Device App Connection Summary API is designed for system administrators and developers who need to monitor and analyze device-to-application connectivity patterns. This API provides aggregated data about how devices in your network connect to various applications, including connection frequencies, success rates, and usage statistics.

**Key Features:**
- **Connection Analytics:** Track how often devices connect to specific applications
- **Performance Monitoring:** Monitor connection success rates and identify problematic connections
- **Usage Patterns:** Understand peak usage times and connection trends
- **Network Optimization:** Identify underutilized or overloaded connections

**Common Integration Scenarios:**
- Building administrative dashboards that display device connectivity health
- Creating automated alerts for connection failures or unusual patterns
- Generating reports for network capacity planning and optimization
- Monitoring device fleet performance and application usage

The data returned by this API is typically aggregated over time periods and can be filtered by various parameters to focus on specific devices, applications, or time ranges.

---

## Endpoints

<a id="get-device_app_connection_summary"></a>

### GET /device_app_connection_summary/

**Description:** Retrieves a comprehensive summary of device-to-application connections, including connection counts, success rates, and usage statistics. This endpoint provides aggregated data that helps administrators understand connectivity patterns and identify potential issues or optimization opportunities.

**Use Cases:**
- Generate daily/weekly/monthly connection reports for management
- Monitor device fleet connectivity health and performance
- Identify devices or applications with connection issues
- Track usage patterns to optimize network resources
- Create automated alerts for connection anomalies

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/device_app_connection_summary/?time_period=7d&device_type=mobile&limit=50
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| time_period | string | query | No | Time range for summary data (1d, 7d, 30d, 90d). Default: 7d |
| device_type | string | query | No | Filter by device type (mobile, desktop, tablet, iot) |
| app_category | string | query | No | Filter by application category |
| organization | string | query | No | Filter by organization ID or name |
| status | string | query | No | Filter by connection status (active, failed, disconnected) |
| limit | integer | query | No | Number of results to return (max 100). Default: 20 |
| offset | integer | query | No | Number of results to skip for pagination. Default: 0 |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/device_app_connection_summary/?time_period=30d&limit=25" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 156,
  "next": "https://gate.zequenze.com/api/v1/device_app_connection_summary/?limit=25&offset=25",
  "previous": null,
  "summary_period": {
    "start_date": "2024-01-01T00:00:00Z",
    "end_date": "2024-01-31T23:59:59Z",
    "period": "30d"
  },
  "results": [
    {
      "device_id": "dev_12345",
      "device_name": "iPhone-Marketing-001",
      "device_type": "mobile",
      "organization": "Marketing Department",
      "app_connections": [
        {
          "app_id": "app_67890",
          "app_name": "Salesforce Mobile",
          "app_category": "CRM",
          "total_connections": 342,
          "successful_connections": 338,
          "failed_connections": 4,
          "success_rate": 98.8,
          "avg_connection_duration": 1847,
          "last_connection": "2024-01-31T14:22:15Z",
          "data_transferred_mb": 125.7
        },
        {
          "app_id": "app_54321",
          "app_name": "Slack",
          "app_category": "Communication",
          "total_connections": 891,
          "successful_connections": 889,
          "failed_connections": 2,
          "success_rate": 99.8,
          "avg_connection_duration": 3600,
          "last_connection": "2024-01-31T16:45:33Z",
          "data_transferred_mb": 89.3
        }
      ],
      "device_summary": {
        "total_connections": 1233,
        "overall_success_rate": 99.4,
        "total_data_transferred_mb": 215.0,
        "most_used_app": "Slack",
        "connection_trend": "stable"
      }
    },
    {
      "device_id": "dev_67891",
      "device_name": "Desktop-IT-005",
      "device_type": "desktop",
      "organization": "IT Department",
      "app_connections": [
        {
          "app_id": "app_11223",
          "app_name": "Azure DevOps",
          "app_category": "Development",
          "total_connections": 156,
          "successful_connections": 154,
          "failed_connections": 2,
          "success_rate": 98.7,
          "avg_connection_duration": 7200,
          "last_connection": "2024-01-31T17:30:00Z",
          "data_transferred_mb": 445.2
        }
      ],
      "device_summary": {
        "total_connections": 156,
        "overall_success_rate": 98.7,
        "total_data_transferred_mb": 445.2,
        "most_used_app": "Azure DevOps",
        "connection_trend": "increasing"
      }
    }
  ],
  "aggregate_stats": {
    "total_devices": 156,
    "total_applications": 24,
    "overall_success_rate": 97.6,
    "total_data_transferred_gb": 12.7,
    "top_performing_apps": [
      {
        "app_name": "Slack",
        "success_rate": 99.8
      },
      {
        "app_name": "Office 365",
        "success_rate": 99.2
      }
    ],
    "devices_with_issues": 8
  }
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns connection summary data |
| 400 | Bad Request - Invalid parameters (e.g., invalid time_period format) |
| 401 | Unauthorized - Invalid or missing Bearer token |
| 403 | Forbidden - Insufficient permissions to access connection data |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error - Server error processing the request |

---

## Common Use Cases

### Use Case 1: Daily Connection Health Dashboard
Retrieve connection summaries for the past 24 hours to display on an administrative dashboard, showing which devices and applications are experiencing connection issues and overall network health metrics.

### Use Case 2: Monthly Performance Reports
Generate comprehensive monthly reports showing connection trends, data usage patterns, and device performance metrics for management review and capacity planning.

### Use Case 3: Proactive Issue Detection
Monitor connection success rates and identify devices or applications with declining performance, enabling proactive troubleshooting before users experience significant issues.

### Use Case 4: Usage Pattern Analysis
Analyze connection data across different time periods to understand peak usage times, optimize resource allocation, and plan for infrastructure scaling.

### Use Case 5: Compliance and Audit Reporting
Generate detailed connection logs and usage statistics for compliance audits, security reviews, and organizational policy enforcement.

---

## Best Practices

- **Pagination Strategy:** Use reasonable limit values (20-50) for better performance. The API supports up to 100 results per request, but smaller batches often provide better response times.

- **Time Period Selection:** Choose appropriate time periods based on your use case. Use shorter periods (1d, 7d) for real-time monitoring and longer periods (30d, 90d) for trend analysis.

- **Caching Recommendations:** Connection summary data is typically updated every 15 minutes. Implement client-side caching with appropriate TTL to reduce API calls and improve application performance.

- **Error Handling:** Always check the success_rate and failed_connections fields to identify problematic devices or applications. Implement alerts for success rates below acceptable thresholds (typically < 95%).

- **Rate Limiting:** The API is rate-limited to prevent abuse. Implement exponential backoff for 429 responses and consider batching requests during off-peak hours for large data pulls.

- **Filtering Optimization:** Use specific filters (device_type, organization, app_category) to reduce response payload size and improve query performance when you need targeted data.

- **Data Interpretation:** Pay attention to the connection_trend field in device summaries to identify devices that may need attention or optimization, and use aggregate_stats for overall system health monitoring.

# Device App Locations

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/device_app_locations/`](#get-device_app_locations) | <a href="https://gate.zequenze.com/api#/device_app_locations/device_app_locations_list" target="_blank">Swagger ↗</a> |

---
> The Device App Locations API provides comprehensive location management functionality for tracking and organizing physical locations within your organization. This API enables you to retrieve location data with filtering capabilities, manage location hierarchies, and access detailed geographic and organizational information for each location.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Device App Locations API is designed to manage physical locations where devices, equipment, or organizational assets are deployed. This API category serves as the foundation for location-based tracking, reporting, and asset management within the GATE platform.

**Key Features:**
- Retrieve comprehensive location listings with pagination support
- Filter locations by modification date for synchronization workflows
- Access detailed geographic information including coordinates and address data
- Manage location hierarchies with organizational context
- Support for both active and inactive location tracking

**Common Integration Scenarios:**
- Asset management systems need to track device locations across multiple facilities
- Inventory applications require location data for warehouse and facility management
- Reporting systems need to generate location-based analytics and summaries
- Mobile applications need to display nearby facilities or service locations
- Synchronization processes need to identify recently updated location records

The API follows REST principles with consistent JSON responses and standard HTTP status codes, making it easy to integrate with existing systems and workflows.

---

## Endpoints

<a id="get-device_app_locations"></a>

### GET /device_app_locations/

**Description:** Retrieves a paginated list of all locations within your organization. This endpoint provides comprehensive location data including geographic coordinates, address information, organizational context, and metadata. It supports filtering by modification date, making it ideal for synchronization processes and incremental data updates.

**Use Cases:**
- Populate location dropdowns in device management interfaces
- Synchronize location data with external asset management systems
- Generate location-based reports and analytics dashboards
- Build facility finder applications with geographic search capabilities
- Monitor location configuration changes over time

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/device_app_locations/?limit=50&offset=0&last_change__gte=2024-01-01T00:00:00Z
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| last_change__gte | string | query | No | Filter locations modified on or after this date/time (ISO 8601 format). Useful for incremental synchronization |
| limit | integer | query | No | Number of results to return per page (default varies, recommended: 10-100) |
| offset | integer | query | No | The initial index from which to return results for pagination |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/device_app_locations/?limit=25&last_change__gte=2024-01-15T00:00:00Z" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 156,
  "next": "https://gate.zequenze.com/api/v1/device_app_locations/?limit=25&offset=25&last_change__gte=2024-01-15T00:00:00Z",
  "previous": null,
  "results": [
    {
      "id": 1001,
      "name": "Downtown Corporate Headquarters",
      "short_name": "downtown-hq",
      "is_active": true,
      "description": "Main corporate office building with executive suites, IT operations center, and primary data center facilities",
      "organization_id": "org_abc123def456",
      "thumbnail": "https://gate.zequenze.com/media/locations/thumbnails/downtown-hq.jpg",
      "address": "500 Technology Drive, Suite 100",
      "reference": "BLDG-001-HQ",
      "city": "San Francisco",
      "postal_code": "94107",
      "state": "California",
      "region": "Bay Area",
      "country_code": "US",
      "latitude": "37.7749",
      "longitude": "-122.4194",
      "created": "2023-03-15T09:30:00Z",
      "last_change": "2024-01-20T14:45:33Z"
    },
    {
      "id": 1002,
      "name": "Manufacturing Plant North",
      "short_name": "plant-north",
      "is_active": true,
      "description": "Primary manufacturing facility for hardware production and quality assurance testing",
      "organization_id": "org_abc123def456",
      "thumbnail": "https://gate.zequenze.com/media/locations/thumbnails/plant-north.jpg",
      "address": "1200 Industrial Boulevard",
      "reference": "MFG-PLANT-N01",
      "city": "Portland",
      "postal_code": "97201",
      "state": "Oregon",
      "region": "Pacific Northwest",
      "country_code": "US",
      "latitude": "45.5152",
      "longitude": "-122.6784",
      "created": "2023-05-22T11:15:00Z",
      "last_change": "2024-01-18T16:22:15Z"
    },
    {
      "id": 1003,
      "name": "Remote Sales Office - Austin",
      "short_name": "sales-austin",
      "is_active": false,
      "description": "Former regional sales office, relocated operations to Dallas facility",
      "organization_id": "org_abc123def456",
      "thumbnail": null,
      "address": "750 Business Center Drive",
      "reference": "SALES-ATX-03",
      "city": "Austin",
      "postal_code": "78759",
      "state": "Texas",
      "region": "South Central",
      "country_code": "US",
      "latitude": "30.2672",
      "longitude": "-97.7431",
      "created": "2023-01-10T08:00:00Z",
      "last_change": "2024-01-16T10:30:45Z"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated location data |
| 400 | Bad Request - Invalid query parameters (e.g., malformed date) |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions to access location data |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error - Server-side processing error |

---

## Common Use Cases

### Use Case 1: Device Assignment Dashboard
Build an interface where administrators can assign devices to specific locations. Use this endpoint to populate location dropdown menus with active facilities, showing both the full name for clarity and short_name for compact displays.

### Use Case 2: Incremental Data Synchronization
Implement a scheduled sync process that periodically checks for location updates using the `last_change__gte` parameter. This enables efficient data synchronization without downloading the entire location dataset each time.

### Use Case 3: Geographic Asset Mapping
Create interactive maps showing asset distribution across facilities using the latitude/longitude coordinates. Combine location data with device counts to visualize organizational presence and asset density.

### Use Case 4: Location-Based Reporting
Generate facility utilization reports by filtering locations based on active status and grouping by region or state. Use the reference codes for consistent identification across different reporting systems.

### Use Case 5: Mobile Field Service Applications
Build mobile apps that help technicians find nearby service locations using geographic coordinates. Filter for active locations only and use thumbnail images to help with visual identification of facilities.

---

## Best Practices

**Pagination Management:**
- Use reasonable page sizes (25-100 records) to balance performance and network efficiency
- Always handle the `next` and `previous` URLs for navigation rather than manually calculating offsets
- Monitor the `count` field to understand total dataset size for progress indicators

**Efficient Data Synchronization:**
- Implement incremental sync using `last_change__gte` with the timestamp from your last successful sync
- Store the `last_change` timestamp from the most recently updated record for the next sync cycle
- Consider implementing exponential backoff for failed sync attempts

**Geographic Data Handling:**
- Validate latitude/longitude coordinates before using them in mapping applications
- Handle cases where geographic coordinates might be null for some locations
- Consider implementing geocoding fallbacks using the address fields when coordinates are missing

**Performance Optimization:**
- Cache frequently accessed location data locally with appropriate TTL based on your update frequency
- Use the `is_active` field to filter out decommissioned locations in user-facing interfaces
- Index location data by commonly filtered fields like `short_name` or `reference` for faster lookups

**Error Handling:**
- Implement proper retry logic for transient errors (429, 500 status codes)
- Validate date parameters client-side before sending requests to avoid 400 errors
- Handle cases where locations might be deleted between API calls (404 responses)

---

# Device App Register

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `POST` | [`/device_app_register/`](#post-device_app_register) | <a href="https://gate.zequenze.com/api#/device_app_register/device_app_register_create" target="_blank">Swagger ↗</a> |

---
> The Device App Register API provides functionality for registering mobile and desktop applications with the backend system. This endpoint captures comprehensive device and user information including hardware identifiers, network details, operating system information, and user credentials for device enrollment and management purposes.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Device App Register API is designed for initial device and application enrollment in the Zequenze platform. This API category handles the critical first step of device onboarding, where mobile apps, desktop applications, or other client software register themselves and their associated devices with the backend system.

**Key Capabilities:**
- **Device Identification**: Captures multiple hardware identifiers (IMEI, IMSI, ICCID, MAC address) for comprehensive device tracking
- **Operating System Detection**: Records detailed OS information including family, version, and API level
- **Network Context**: Identifies home mobile network information and carrier details
- **User Association**: Links devices to user accounts with flexible authentication options
- **Device Categorization**: Supports classification across device types (desktop, laptop, tablet, mobile phone)

**Common Integration Scenarios:**
- Mobile app first-launch registration
- Desktop application installation and activation
- IoT device provisioning and enrollment
- User device inventory management
- Compliance and security auditing

The registration process typically occurs during application installation or first run, establishing the device identity that will be used for subsequent API interactions, push notifications, and device management operations.

---

## Endpoints

<a id="post-device_app_register"></a>

### POST /device_app_register/

**Description:** Registers a new device and application instance with the backend system. This endpoint should be called during app installation or first launch to establish the device identity and associate it with user credentials. The registration captures comprehensive device information for inventory management, security tracking, and push notification delivery.

**Use Cases:**
- Mobile app first-time setup and device enrollment
- Desktop application activation and licensing
- IoT device provisioning in enterprise environments
- User device inventory for compliance and security auditing
- Establishing push notification delivery channels

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/device_app_register/
```

**Request Body Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| number | string | No | Device phone number (MSISDN) for mobile devices |
| generic_id | string | No | Unique identifier from OS/App store (e.g., Android ID, iOS IDFA) |
| imei | string | No | International Mobile Equipment Identity for cellular devices |
| imsi | string | No | International Mobile Subscriber Identity from SIM card |
| iccid | string | No | Integrated Circuit Card Identifier from SIM card |
| mac_addr | string | No | MAC address of primary network interface |
| home_mobile_network_name | string | No | Carrier name (e.g., "Verizon", "AT&T", "Vodafone") |
| home_mobile_network_mccmnc | string | No | Mobile Country Code and Mobile Network Code (e.g., "310410") |
| app_version | string | No | Version of the registering application |
| os_family | string | No | Operating system family (e.g., "Android", "iOS", "Windows", "macOS") |
| os_version | string | No | Operating system version (e.g., "14.0", "Windows 11") |
| os_api_version | string | No | OS API level or SDK version |
| device_family | string | No | Device family or series (e.g., "iPhone", "Galaxy", "ThinkPad") |
| device_brand | string | No | Device manufacturer (e.g., "Apple", "Samsung", "Lenovo") |
| device_model | string | No | Specific device model (e.g., "iPhone 15 Pro", "Galaxy S24") |
| device_type | string | No | Device category: 'de' (Desktop), 'la' (Laptop), 'tb' (Tablet), 'ph' (Mobile phone) |
| push_key | string | No | Push notification token for message delivery |
| username | string | No | User account username for device association |
| password | string | No | User account password for authentication |
| user_external_id | string | No | External system user identifier for integration |
| user_class | string | No | User classification or service tier |

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/device_app_register/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "number": "+1234567890",
    "generic_id": "android-id-12345",
    "imei": "123456789012345",
    "mac_addr": "00:1B:44:11:3A:B7",
    "home_mobile_network_name": "Verizon Wireless",
    "home_mobile_network_mccmnc": "311480",
    "app_version": "2.1.0",
    "os_family": "Android",
    "os_version": "14.0",
    "os_api_version": "34",
    "device_family": "Galaxy",
    "device_brand": "Samsung",
    "device_model": "Galaxy S24",
    "device_type": "ph",
    "push_key": "fcm-token-abc123xyz789",
    "username": "john.doe",
    "password": "securePassword123",
    "user_class": "premium"
  }'
```

**Example Response:**
```json
{
  "number": "+1234567890",
  "generic_id": "android-id-12345",
  "imei": "123456789012345",
  "imsi": "311480123456789",
  "iccid": "89014103271234567890",
  "mac_addr": "00:1B:44:11:3A:B7",
  "home_mobile_network_name": "Verizon Wireless",
  "home_mobile_network_mccmnc": "311480",
  "app_version": "2.1.0",
  "os_family": "Android",
  "os_version": "14.0",
  "os_api_version": "34",
  "device_family": "Galaxy",
  "device_brand": "Samsung",
  "device_model": "Galaxy S24",
  "device_type": "ph",
  "push_key": "fcm-token-abc123xyz789",
  "username": "john.doe",
  "user_external_id": "ext-user-456",
  "user_class": "premium"
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - Device successfully registered with the system |
| 400 | Bad Request - Invalid data format or missing required fields |
| 401 | Unauthorized - Invalid or missing authentication token |
| 409 | Conflict - Device already registered (duplicate IMEI/MAC address) |
| 422 | Unprocessable Entity - Valid format but business logic validation failed |

---

## Common Use Cases

### Use Case 1: Mobile App First Launch Registration
When a user installs and first opens a mobile app, the application collects device information and registers with the backend. This establishes the device identity for future API calls and enables push notifications.

**Required endpoints:** POST /device_app_register/

### Use Case 2: Enterprise Device Enrollment
IT administrators deploying company devices use the registration API to enroll devices in the corporate management system, associating them with employee accounts and applying appropriate device policies.

**Required endpoints:** POST /device_app_register/

### Use Case 3: IoT Device Provisioning
Smart devices and IoT endpoints register themselves during initial setup, providing hardware identifiers and network information for device management and monitoring.

**Required endpoints:** POST /device_app_register/

### Use Case 4: Cross-Platform Device Inventory
Applications running on multiple platforms (mobile, desktop, web) register their host devices to maintain a unified inventory across all user touchpoints for security and compliance reporting.

**Required endpoints:** POST /device_app_register/

### Use Case 5: Push Notification Setup
Mobile and desktop applications register their push notification tokens during the device registration process, enabling the backend to deliver messages and alerts to specific devices.

**Required endpoints:** POST /device_app_register/

---

## Best Practices

- **Privacy Compliance**: Only collect device identifiers that are necessary for your use case. Be aware of privacy regulations (GDPR, CCPA) when collecting IMEI, MAC addresses, or other persistent identifiers.

- **Unique Device Identification**: Use multiple identifiers when available (IMEI + MAC address + generic_id) to create robust device fingerprinting while having fallback options if some identifiers are unavailable.

- **Secure Credential Handling**: If passing username/password in registration, ensure the API connection uses HTTPS and consider using temporary tokens or OAuth flows instead of permanent passwords.

- **Device Type Classification**: Always specify the device_type parameter to enable proper device management policies and user experience optimization based on device capabilities.

- **Error Handling**: Implement retry logic for network failures, but avoid re-registering devices that return 409 (Conflict) responses, as this indicates the device is already known to the system.

- **Push Token Management**: Keep push_key tokens updated as they can expire or change when apps are updated or reinstalled. Consider implementing a separate endpoint update mechanism for token refresh.

- **Data Validation**: Validate device identifiers format before sending (e.g., IMEI should be 15 digits, MAC addresses should follow standard format) to avoid unnecessary API calls and improve registration success rates.

---

# Device App Test Report

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `POST` | [`/device_app_test_report/`](#post-device_app_test_report) | <a href="https://gate.zequenze.com/api#/device_app_test_report/device_app_test_report_create" target="_blank">Swagger ↗</a> |

---
> The Device App Test Report API enables mobile and desktop applications to submit network performance test results to the GATE platform. This endpoint allows developers to register test data including download/upload speeds, latency, jitter, and DNS response times across different network types like WiFi, mobile, Bluetooth, and Ethernet.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Device App Test Report API provides a centralized way to collect and store network performance metrics from client applications. This API is designed for applications that perform network diagnostics, speed tests, or connectivity monitoring and need to report their findings to a central analytics platform.

**Key Features:**
- Support for multiple network types (WiFi, Mobile, Bluetooth, Ethernet)
- Multiple test types including bandwidth, latency, jitter, and DNS performance
- Flexible destination targeting (URLs, hostnames, IP addresses)
- Standardized units and result formatting
- Batch test result reporting with count tracking

**Common Integration Scenarios:**
- Mobile apps performing periodic connectivity tests
- Network monitoring tools reporting performance metrics
- IoT devices submitting connectivity health data
- Desktop applications measuring network quality
- Quality assurance tools validating network performance

The API uses standardized abbreviations for network and test types to ensure consistent data collection across different client implementations.

---

## Endpoints

<a id="post-device_app_test_report"></a>

### POST /device_app_test_report/

**Description:** Submits network test results from client applications to the GATE platform. This endpoint accepts test data including network performance metrics, test metadata, and result values. Use this endpoint when your application has completed network tests and needs to report the results for analytics, monitoring, or troubleshooting purposes.

**Use Cases:**
- Mobile speed test apps reporting download/upload results
- Network monitoring tools submitting latency measurements
- IoT devices reporting connectivity health metrics
- Quality assurance applications validating network performance
- Diagnostic tools measuring DNS response times

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/device_app_test_report/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| data | string | body | Yes | JSON string containing the test report data with network type, test type, destination, and results |

**Request Body Schema:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| network_name | string | No | Name of the current network (e.g., "Office WiFi", "Verizon LTE") |
| network_type | string | Yes | Network type code: 'wi' (WiFi), 'mo' (Mobile), 'bl' (Bluetooth), 'et' (Ethernet) |
| test_type | string | Yes | Test type code: 'dl' (Download), 'ul' (Upload), 'de' (Delay), 'jt' (Jitter), 'dn' (DNS response time) |
| destination | string | Yes | Target for the test: URL, hostname, or IP address |
| value | number | Yes | Numeric test result value |
| count | integer | No | Number of test iterations performed (useful for averaged results) |
| unit | string | No | Unit of measurement: 'Kbps' (Kilobits/sec), 'KBps' (Kilobytes/sec), 'ms' (Milliseconds) |

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/device_app_test_report/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "network_name": "Office WiFi",
    "network_type": "wi",
    "test_type": "dl",
    "destination": "speedtest.example.com",
    "value": 95.7,
    "count": 3,
    "unit": "Kbps"
  }'
```

**Example Request Bodies:**

**Download Speed Test:**
```json
{
  "network_name": "Home WiFi 5GHz",
  "network_type": "wi",
  "test_type": "dl",
  "destination": "cdn.speedtest.net",
  "value": 150.5,
  "count": 5,
  "unit": "Kbps"
}
```

**Mobile Network Latency Test:**
```json
{
  "network_name": "T-Mobile 5G",
  "network_type": "mo",
  "test_type": "de",
  "destination": "8.8.8.8",
  "value": 45.2,
  "count": 10,
  "unit": "ms"
}
```

**DNS Response Time Test:**
```json
{
  "network_type": "et",
  "test_type": "dn",
  "destination": "google.com",
  "value": 12.8,
  "count": 1,
  "unit": "ms"
}
```

**Example Response (201 Created):**
```json
{
  "id": 12847,
  "network_name": "Office WiFi",
  "network_type": "wi",
  "test_type": "dl",
  "destination": "speedtest.example.com",
  "value": 95.7,
  "count": 3,
  "unit": "Kbps",
  "timestamp": "2024-01-15T14:32:18Z",
  "status": "processed"
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - Test report successfully registered |
| 400 | Bad Request - Invalid data format or missing required fields |
| 401 | Unauthorized - Invalid or missing API token |
| 422 | Unprocessable Entity - Valid JSON but invalid field values |
| 500 | Internal Server Error - Server processing error |

---

## Common Use Cases

### Use Case 1: Mobile Speed Testing Application
A mobile app that performs periodic network speed tests and reports results to monitor carrier performance across different locations and times.

```bash
# Report download speed test
POST /device_app_test_report/ with mobile network download data
```

### Use Case 2: IoT Device Connectivity Monitoring
IoT devices that need to report their network connectivity quality for remote monitoring and troubleshooting purposes.

```bash
# Report connectivity health metrics
POST /device_app_test_report/ with latency and DNS response data
```

### Use Case 3: Enterprise Network Quality Assurance
Corporate applications that validate network performance across office locations to ensure adequate connectivity for business applications.

```bash
# Report comprehensive network tests
POST /device_app_test_report/ with WiFi/Ethernet performance data
```

### Use Case 4: Gaming Application Latency Monitoring
Gaming platforms that measure and report network latency to game servers for matchmaking and performance optimization.

```bash
# Report game server latency
POST /device_app_test_report/ with jitter and delay measurements
```

### Use Case 5: Network Diagnostic Tools
Diagnostic applications that perform comprehensive network tests and need to centralize results for analysis and reporting.

```bash
# Report multi-test diagnostic results
POST /device_app_test_report/ with various test types and destinations
```

---

## Best Practices

- **Standardize Network Names**: Use consistent naming conventions for network_name to enable better analytics (e.g., "Office_WiFi_5GHz" rather than varying formats)

- **Batch Related Tests**: When performing multiple test types on the same network, submit separate reports for each test type to maintain data clarity

- **Include Test Counts**: Always specify the count parameter when averaging multiple test runs to provide context for result reliability

- **Use Appropriate Units**: Match units to test types - use 'ms' for latency/jitter/DNS tests, 'Kbps' or 'KBps' for throughput tests

- **Handle Network Transitions**: Be aware that network_type may change during testing on mobile devices; submit separate reports when network switches occur

- **Error Handling**: Implement retry logic for failed submissions, especially on mobile networks where connectivity may be intermittent

- **Data Validation**: Validate test results before submission to avoid reporting obviously invalid values (e.g., negative latency, impossibly high speeds)

- **Privacy Considerations**: Be mindful of including sensitive information in network_name or destination fields, especially for enterprise deployments

---

# Device App User Authenticate

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `POST` | [`/device_app_user_authenticate/`](#post-device_app_user_authenticate) | <a href="https://gate.zequenze.com/api#/device_app_user_authenticate/device_app_user_authenticate_create" target="_blank">Swagger ↗</a> |

---
> The Device App User Authentication endpoint provides secure credential validation for user authentication within device applications. This endpoint validates username and password combinations and is typically used during login flows for mobile or desktop applications that need to authenticate users against the GATE system.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Device App User Authenticate API category provides a single, focused endpoint for validating user credentials in device applications. This endpoint is designed to handle authentication requests from mobile apps, desktop applications, or IoT devices that need to verify user credentials against the GATE authentication system.

This endpoint accepts user credentials (username and password) and validates them against the system's user database. It's commonly used in scenarios where applications need to authenticate users before granting access to protected resources or functionality. The endpoint follows secure authentication practices and should be used over HTTPS connections to protect credential transmission.

Key features include:
- Secure credential validation
- Support for username/password authentication
- Integration with device applications
- RESTful API design for easy integration

---

## Endpoints

<a id="post-device_app_user_authenticate"></a>

### POST /device_app_user_authenticate/

**Description:** Validates user credentials by accepting a username and password combination and returning authentication results. This endpoint is specifically designed for device applications that need to authenticate users before granting access to protected features or data.

**Use Cases:**
- Mobile app login screens where users enter credentials
- Desktop application authentication flows
- IoT device user validation before accessing device features
- Single sign-on integration for device applications
- User credential verification in embedded systems

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/device_app_user_authenticate/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| data | string | body | Yes | JSON string containing user authentication credentials (username and password) |

**Request Body Schema:**
```json
{
  "username": "string (required)",
  "password": "string (required)"
}
```

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/device_app_user_authenticate/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john.doe@company.com",
    "password": "SecurePassword123!"
  }'
```

**Example Request Body:**
```json
{
  "username": "john.doe@company.com",
  "password": "SecurePassword123!"
}
```

**Example Response (Success):**
```json
{
  "username": "john.doe@company.com",
  "authenticated": true,
  "user_id": 12345,
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_expires": "2024-01-15T18:30:00Z",
  "user_profile": {
    "first_name": "John",
    "last_name": "Doe",
    "email": "john.doe@company.com",
    "role": "device_user",
    "permissions": ["device_access", "data_view"]
  }
}
```

**Example Response (Failed Authentication):**
```json
{
  "username": "john.doe@company.com",
  "authenticated": false,
  "error": "Invalid credentials",
  "error_code": "AUTH_FAILED"
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - Authentication successful, user credentials validated |
| 400 | Bad Request - Missing or invalid username/password format |
| 401 | Unauthorized - Invalid API token or authentication failed |
| 422 | Unprocessable Entity - Valid request format but authentication failed |
| 429 | Too Many Requests - Rate limit exceeded for authentication attempts |
| 500 | Internal Server Error - Server error during authentication process |

---

## Common Use Cases

### Use Case 1: Mobile App Login
When developing a mobile application that requires user authentication, use this endpoint during the login flow. After users enter their credentials, send them to this endpoint for validation and receive an access token for subsequent API calls.

### Use Case 2: IoT Device User Verification
For IoT devices with user interfaces, this endpoint can verify that users have valid credentials before allowing access to device configuration or sensitive data.

### Use Case 3: Desktop Application Authentication
Desktop applications can integrate this endpoint into their login screens to authenticate users against the centralized GATE user database, enabling consistent user management across platforms.

### Use Case 4: Kiosk or Embedded System Login
Public kiosks or embedded systems can use this endpoint to authenticate users before providing access to personalized content or restricted functionality.

### Use Case 5: Third-Party Application Integration
External applications integrating with the GATE system can use this endpoint to authenticate users and maintain consistent user sessions across multiple platforms.

---

## Best Practices

- **Secure Transmission**: Always use HTTPS when transmitting credentials to protect sensitive user data during authentication requests.

- **Error Handling**: Implement proper error handling for different response codes. Don't expose detailed error messages to end users that might reveal system information.

- **Rate Limiting**: Implement client-side rate limiting to prevent excessive authentication attempts, which could trigger server-side rate limits or security measures.

- **Token Management**: Store received access tokens securely on the device and implement proper token refresh mechanisms when tokens expire.

- **Input Validation**: Validate username and password format on the client side before sending requests to reduce unnecessary API calls and improve user experience.

- **Credential Security**: Never log or store user passwords in plain text. Hash sensitive data and follow secure coding practices for credential handling.

- **Session Management**: Implement proper session timeout handling and allow users to securely log out, invalidating their access tokens.

- **Retry Logic**: Implement exponential backoff for failed authentication attempts to handle temporary network issues gracefully while respecting rate limits.

# Device App User Update

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `POST` | [`/device_app_user_update/`](#post-device_app_user_update) | <a href="https://gate.zequenze.com/api#/device_app_user_update/device_app_user_update_create" target="_blank">Swagger ↗</a> |

---
> The device_app_user_update API endpoint allows mobile applications and device management systems to update user information associated with devices. This endpoint is essential for maintaining accurate user profiles, device associations, and subscriber data in mobile network environments.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The device_app_user_update API category provides functionality for updating comprehensive user information linked to mobile devices and network subscribers. This endpoint is particularly valuable for:

- **Mobile Network Operators (MNOs)** managing subscriber data and device associations
- **Device Management Platforms** updating user profiles and device bindings
- **Mobile Applications** syncing user credentials and device identifiers
- **IoT Systems** maintaining device-to-user mappings

The endpoint supports updating critical identifiers including device numbers (MSISDN), hardware identifiers (IMEI, IMSI, ICCID), user credentials, and service classifications. This comprehensive approach ensures that all aspects of the user-device relationship can be maintained accurately across the system.

Common scenarios include user onboarding, device transfers between users, credential updates, and service class modifications. The endpoint is designed to handle both individual field updates and bulk profile modifications efficiently.

---

## Endpoints

<a id="post-device_app_user_update"></a>

### POST /device_app_user_update/

**Description:** Updates comprehensive user information associated with a device, including network identifiers, hardware identifiers, user credentials, and service classifications. This endpoint is essential for maintaining accurate user-device relationships in mobile networks and device management systems.

**Use Cases:**
- Update user credentials when a subscriber changes their login information
- Associate a new device with an existing user account during device upgrades
- Modify service class when a user changes their subscription plan
- Update network identifiers during SIM card replacements or number porting

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/device_app_user_update/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| data | string | body | Yes | JSON string containing user and device information to update |

**Request Body Fields:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| number | string | No | Device number (MSISDN) - the phone number associated with the device |
| generic_id | string | No | Generic unique identifier from the operating system or app store |
| imei | string | No | International Mobile Equipment Identity - unique device hardware identifier |
| imsi | string | No | International Mobile Subscriber Identity - unique SIM card identifier |
| iccid | string | No | Integrated Circuit Card Identifier - unique SIM card serial number |
| username | string | No | User's login username for authentication |
| password | string | No | User's password (should be properly hashed) |
| user_external_id | string | No | External system identifier for the user |
| user_class | string | No | User's class of service (e.g., "premium", "standard", "basic") |

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/device_app_user_update/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "data": "{\"number\":\"+1234567890\",\"username\":\"john.doe\",\"user_class\":\"premium\",\"imei\":\"123456789012345\",\"user_external_id\":\"ext_12345\"}"
  }'
```

**Example Request Body:**
```json
{
  "data": "{\"number\":\"+1234567890\",\"generic_id\":\"com.example.app.user123\",\"imei\":\"123456789012345\",\"imsi\":\"310260123456789\",\"iccid\":\"89014103211118510720\",\"username\":\"john.doe\",\"password\":\"$2a$10$N9qo8uLOickgx2ZMRZoMye\",\"user_external_id\":\"ext_12345\",\"user_class\":\"premium\"}"
}
```

**Example Response (201 Created):**
```json
{
  "number": "+1234567890",
  "generic_id": "com.example.app.user123",
  "imei": "123456789012345",
  "imsi": "310260123456789",
  "iccid": "89014103211118510720",
  "username": "john.doe",
  "password": "$2a$10$N9qo8uLOickgx2ZMRZoMye",
  "user_external_id": "ext_12345",
  "user_class": "premium",
  "updated_at": "2024-01-15T10:30:00Z",
  "status": "success"
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - User information successfully updated |
| 400 | Bad Request - Invalid data format or missing required fields |
| 401 | Unauthorized - Invalid or missing authentication token |
| 422 | Unprocessable Entity - Data validation errors |
| 500 | Internal Server Error - Server-side processing error |

---

## Common Use Cases

### Use Case 1: User Credential Update
When a user changes their login credentials, update their username and password while maintaining device associations. This ensures continued access while preserving all device-specific identifiers.

### Use Case 2: Device Upgrade
During a device upgrade, transfer user information to the new device by updating the IMEI and other hardware identifiers while keeping the user credentials and service class intact.

### Use Case 3: Service Plan Change
When a user upgrades or downgrades their service plan, update the user_class field to reflect their new subscription tier, enabling appropriate service provisioning.

### Use Case 4: SIM Card Replacement
After replacing a damaged or lost SIM card, update the IMSI and ICCID values while maintaining all other user information and device associations.

### Use Case 5: External System Integration
Synchronize user data with external CRM or billing systems by updating the user_external_id field, enabling cross-platform user tracking and management.

---

## Best Practices

- **Data Validation**: Always validate device identifiers (IMEI, IMSI, ICCID) against industry standards before submission to prevent data corruption
- **Password Security**: Ensure passwords are properly hashed using strong algorithms (bcrypt, Argon2) before sending to the API
- **Partial Updates**: Only include fields that need updating in the request to minimize data transfer and processing time
- **Error Handling**: Implement robust error handling to manage validation failures and network timeouts gracefully
- **Idempotency**: Design your integration to handle duplicate requests safely, as network issues may cause request retries
- **Rate Limiting**: Implement appropriate request throttling to avoid overwhelming the API service
- **Data Privacy**: Ensure compliance with data protection regulations when handling user credentials and personal identifiers
- **Logging**: Maintain audit logs of user updates for security and compliance purposes, but avoid logging sensitive data like passwords

# Hostspot Access Points

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/hostspot_access_points/`](#get-hostspot_access_points) | <a href="https://gate.zequenze.com/api#/hostspot_access_points/hostspot_access_points_list" target="_blank">Swagger ↗</a> |

---
> The Hotspot Access Points API provides endpoints for managing and retrieving information about physical network access point locations within your organization. These endpoints allow you to fetch detailed location data, filter by geographical coordinates, and manage access point metadata for network infrastructure monitoring and reporting.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Hotspot Access Points API enables you to manage and query physical network access point locations across your organization's infrastructure. This API is essential for network administrators, IT teams, and facility managers who need to maintain accurate records of wireless access point deployments.

**Key Features:**
- Retrieve comprehensive access point location data including geographical coordinates
- Filter access points by modification dates and coordinate availability
- Access detailed address information including city, state, postal codes, and country data
- Support for pagination to handle large deployments efficiently
- Integration with organizational structures for multi-tenant environments

**Common Use Cases:**
- Network infrastructure auditing and documentation
- Geographic visualization of access point coverage areas
- Location-based network performance monitoring
- Facility management and space planning
- Compliance reporting for network infrastructure

The API follows REST principles and returns data in JSON format with standardized pagination for list endpoints. All location data includes metadata such as creation dates and last modification times to support change tracking and audit requirements.

---

## Endpoints

<a id="get-hostspot_access_points"></a>

### GET /hostspot_access_points/

**Description:** Retrieves a paginated list of all hotspot access points within your organization. This endpoint provides comprehensive location data including geographical coordinates, address details, and organizational metadata. It's the primary endpoint for discovering and enumerating network access point locations.

**Use Cases:**
- Generate network infrastructure reports showing all access point locations
- Create geographic visualizations of network coverage areas
- Audit access point deployments across multiple facilities
- Export location data for facility management systems
- Monitor recent changes to access point configurations

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/hostspot_access_points/?have_coordinates=true&limit=50&offset=0
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| last_change__gte | string | query | No | Filter results to show only access points modified on or after the specified date. Accepts ISO format: `2000-01-01`, `2000-01-01 00:01:00`, or `2000-01-01 00:01:00+00:00` |
| limit | integer | query | No | Number of results to return per page. Default and maximum values depend on your organization's configuration |
| offset | integer | query | No | The initial index from which to return results. Used for pagination through large datasets |
| have_coordinates | boolean | query | No | When set to `true`, returns only access points that have latitude and longitude coordinates configured |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/hostspot_access_points/?have_coordinates=true&limit=25&last_change__gte=2024-01-01" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 127,
  "next": "https://gate.zequenze.com/api/v1/hostspot_access_points/?limit=25&offset=25",
  "previous": null,
  "results": [
    {
      "id": 1001,
      "name": "Building A - First Floor Lobby",
      "short_name": "bldg-a-lobby",
      "is_active": true,
      "description": "Main entrance lobby access point serving reception area and visitor seating",
      "organization_id": "org-12345",
      "thumbnail": "https://gate.zequenze.com/media/thumbnails/ap_1001.jpg",
      "address": "123 Corporate Drive",
      "reference": "AP-LOBBY-001",
      "city": "San Francisco",
      "postal_code": "94105",
      "state": "California",
      "region": "Bay Area",
      "country_code": "US",
      "latitude": "37.7749",
      "longitude": "-122.4194",
      "created": "2024-01-15T08:30:00Z",
      "last_change": "2024-03-10T14:22:00Z"
    },
    {
      "id": 1002,
      "name": "Building A - Conference Room Alpha",
      "short_name": "conf-alpha",
      "is_active": true,
      "description": "Conference room access point supporting up to 50 simultaneous connections",
      "organization_id": "org-12345",
      "thumbnail": "https://gate.zequenze.com/media/thumbnails/ap_1002.jpg",
      "address": "123 Corporate Drive",
      "reference": "AP-CONF-002",
      "city": "San Francisco",
      "postal_code": "94105",
      "state": "California",
      "region": "Bay Area",
      "country_code": "US",
      "latitude": "37.7751",
      "longitude": "-122.4192",
      "created": "2024-01-15T08:45:00Z",
      "last_change": "2024-02-28T11:15:00Z"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated list of access points |
| 401 | Unauthorized - Invalid or missing Bearer token |
| 403 | Forbidden - Token lacks permission to access this organization's data |
| 422 | Unprocessable Entity - Invalid query parameters (e.g., malformed date format) |

---

## Common Use Cases

### Use Case 1: Network Coverage Mapping
Retrieve all access points with coordinates to create geographic visualizations of network coverage. Use the `have_coordinates=true` parameter to ensure only mappable locations are returned, then plot the latitude/longitude data on mapping platforms.

### Use Case 2: Infrastructure Change Auditing
Monitor recent modifications to access point configurations by filtering with `last_change__gte` parameter. This helps track when locations were updated, moved, or reconfigured for compliance and change management purposes.

### Use Case 3: Facility Management Integration
Export comprehensive location data including full address details and reference codes to integrate with facility management systems. The structured address fields support geocoding and space planning applications.

### Use Case 4: Multi-Location Reporting
Generate organization-wide reports by paginating through all access points across facilities. Use the organization_id field to group results by business units or geographic regions.

### Use Case 5: Network Capacity Planning
Analyze access point distribution and descriptions to identify areas needing additional coverage or capacity upgrades. The is_active field helps distinguish between deployed and decommissioned locations.

---

## Best Practices

- **Pagination Strategy**: For large deployments, use reasonable page sizes (25-100 items) and implement proper pagination handling to avoid timeouts and reduce memory usage
- **Coordinate Filtering**: When building mapping applications, always use `have_coordinates=true` to avoid processing locations without geographic data
- **Date Filtering**: Use `last_change__gte` parameter efficiently by caching previous query timestamps to fetch only recently modified access points
- **Error Handling**: Implement retry logic for 5xx errors and graceful degradation for 4xx errors, particularly when processing large datasets
- **Rate Limiting**: Monitor response times and implement appropriate delays between requests when batch processing access point data
- **Security**: Never log or expose Bearer tokens in client-side code; always handle authentication server-side in production environments
- **Caching**: Consider caching stable access point data (locations rarely change) while refreshing dynamic fields like status and last modification dates more frequently

---

# Hostspot Locations

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/hostspot_locations/`](#get-hostspot_locations) | <a href="https://gate.zequenze.com/api#/hostspot_locations/hostspot_locations_list" target="_blank">Swagger ↗</a> |

---
> The Hotspot Locations API provides access to physical location data for hotspot devices within your organization. This endpoint allows you to retrieve detailed information about locations including geographical coordinates, addresses, and organizational details, making it essential for location-based analytics, mapping applications, and device management systems.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Hotspot Locations API enables you to manage and retrieve location data for hotspot devices across your organization's network infrastructure. This API is particularly useful for:

- **Network Management**: Track and organize physical locations where hotspot devices are deployed
- **Geographic Analytics**: Analyze network usage patterns across different locations and regions
- **Mapping Applications**: Display hotspot locations on interactive maps for administrative dashboards
- **Location-Based Services**: Provide location-aware features and services to end users
- **Compliance & Reporting**: Generate location-based reports for regulatory compliance or business intelligence

The API supports filtering by coordinates, change tracking for synchronization purposes, and comprehensive location metadata including addresses, postal codes, and geographic coordinates. All location data is scoped to your organization and includes both active and inactive locations for complete lifecycle management.

---

## Endpoints

<a id="get-hostspot_locations"></a>

### GET /hostspot_locations/

**Description:** Retrieves a paginated list of all hotspot locations within your organization. This endpoint supports various filtering options to help you find specific locations based on coordinates availability, recent changes, or other criteria. Use this endpoint to populate location dropdowns, generate maps, or synchronize location data with external systems.

**Use Cases:**
- Building a map interface showing all hotspot locations with coordinates
- Synchronizing location data with external systems using the last_change filter
- Generating reports of active vs inactive locations
- Populating location selection interfaces for device management

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/hostspot_locations/?have_coordinates=true&limit=50&offset=0
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| last_change__gte | string | query | No | Filter locations modified since a specific date/time. Use ISO format: `2000-01-01`, `2000-01-01 00:01:00`, or `2000-01-01 00:01:00+00:00` |
| limit | integer | query | No | Number of results to return per page (default pagination applies) |
| offset | integer | query | No | The starting index for results (used for pagination) |
| have_coordinates | boolean | query | No | When `true`, returns only locations with latitude and longitude values set |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/hostspot_locations/?have_coordinates=true&limit=10" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 156,
  "next": "https://gate.zequenze.com/api/v1/hostspot_locations/?limit=10&offset=10",
  "previous": null,
  "results": [
    {
      "id": 1,
      "name": "Downtown Coffee Shop",
      "short_name": "downtown-coffee",
      "is_active": true,
      "description": "High-traffic location in downtown business district",
      "organization_id": "org_12345",
      "thumbnail": "https://gate.zequenze.com/media/thumbnails/location_1.jpg",
      "address": "123 Main Street",
      "reference": "Building A, Ground Floor",
      "city": "San Francisco",
      "postal_code": "94105",
      "state": "California",
      "region": "Bay Area",
      "country_code": "US",
      "latitude": "37.7749",
      "longitude": "-122.4194",
      "created": "2024-01-15T10:30:00Z",
      "last_change": "2024-03-10T14:22:00Z"
    },
    {
      "id": 2,
      "name": "Airport Terminal B",
      "short_name": "airport-terminal-b",
      "is_active": true,
      "description": "International departures terminal hotspot",
      "organization_id": "org_12345",
      "thumbnail": null,
      "address": "San Francisco International Airport",
      "reference": "Terminal B, Gate Area",
      "city": "San Francisco",
      "postal_code": "94128",
      "state": "California",
      "region": "Bay Area",
      "country_code": "US",
      "latitude": "37.6213",
      "longitude": "-122.3790",
      "created": "2024-02-01T08:15:00Z",
      "last_change": "2024-03-05T16:45:00Z"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns the paginated list of hotspot locations |
| 401 | Unauthorized - Invalid or missing Bearer token |
| 403 | Forbidden - Token valid but lacks permission to access locations |
| 422 | Unprocessable Entity - Invalid parameter format (e.g., malformed date) |

---

## Common Use Cases

### Use Case 1: Building a Location Map Dashboard
Retrieve all locations with coordinates to display on an interactive map for network administrators.

```bash
https://gate.zequenze.com/api/v1/hostspot_locations/?have_coordinates=true&is_active=true
```

### Use Case 2: Syncing Location Data
Synchronize location changes since your last update using the timestamp filter for data consistency.

```bash
https://gate.zequenze.com/api/v1/hostspot_locations/?last_change__gte=2024-03-01T00:00:00Z
```

### Use Case 3: Location Selection Interface
Load locations with pagination for device assignment or configuration interfaces.

```bash
https://gate.zequenze.com/api/v1/hostspot_locations/?limit=25&offset=0
```

### Use Case 4: Geographic Analytics
Filter locations by region or coordinates to analyze network coverage and usage patterns.

```bash
https://gate.zequenze.com/api/v1/hostspot_locations/?have_coordinates=true&limit=100
```

### Use Case 5: Inventory Management
Retrieve all locations (active and inactive) for comprehensive device deployment planning.

```bash
https://gate.zequenze.com/api/v1/hostspot_locations/?limit=50
```

---

## Best Practices

- **Use Pagination Effectively**: Always implement pagination for large datasets. Start with reasonable page sizes (25-50 items) and adjust based on your application's performance requirements.

- **Filter by Coordinates**: When building mapping applications, use `have_coordinates=true` to avoid processing locations without geographic data.

- **Implement Change Tracking**: Use the `last_change__gte` parameter for efficient synchronization. Store the timestamp of your last successful sync and use it in subsequent requests.

- **Cache Location Data**: Location information typically changes infrequently, making it ideal for caching. Consider implementing a cache invalidation strategy based on the `last_change` field.

- **Handle Missing Data Gracefully**: Not all locations may have complete address information or coordinates. Design your application to handle optional fields appropriately.

- **Monitor Rate Limits**: Implement proper error handling and retry logic for API rate limits, especially when processing large numbers of locations.

- **Validate Geographic Data**: When using latitude/longitude values, validate that they fall within expected ranges and handle edge cases for locations near poles or the international date line.

---

# Me

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/me/organization/`](#get-me-organization) | <a href="https://gate.zequenze.com/api#/me/me_organization_list" target="_blank">Swagger ↗</a> |

---
> The User Organization API provides access to organization information for the authenticated user. This endpoint allows users to retrieve details about their organization membership, settings, and associated metadata. It's commonly used for displaying organization context in applications and implementing organization-based access controls.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The User Organization API category focuses on retrieving organization-related information for the currently authenticated user. This API is essential for applications that need to understand the organizational context of their users, implement role-based access controls, or display organization-specific information in user interfaces.

Key concepts to understand:
- **User Organization Context**: Each authenticated user belongs to one or more organizations, and this API provides access to that organizational data
- **Organization Metadata**: Includes details like organization name, settings, subscription status, and user permissions within the organization
- **Access Control**: The information returned is filtered based on the user's permissions and role within the organization

This endpoint is typically called during application initialization to establish the user's organizational context and configure the application interface accordingly.

---

## Endpoints

<a id="get-me-organization"></a>

### GET /me/organization/

**Description:** Retrieves comprehensive organization information for the currently authenticated user. This endpoint returns details about the user's organization membership, including organization metadata, user permissions, subscription status, and configuration settings. Use this endpoint to establish organizational context when a user logs into your application.

**Use Cases:**
- Initialize application with user's organization settings and branding
- Determine user's permissions and role within their organization
- Display organization-specific dashboard elements and navigation
- Validate organization subscription status and feature access
- Configure organization-specific integrations and settings

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/me/organization/
```

**Parameters:**

This endpoint does not accept any query parameters.

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/me/organization/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "id": 12345,
  "name": "Acme Corporation",
  "slug": "acme-corp",
  "display_name": "Acme Corporation",
  "description": "Leading provider of industrial solutions",
  "website": "https://www.acmecorp.com",
  "industry": "Manufacturing",
  "size": "enterprise",
  "created_at": "2023-03-15T08:30:00Z",
  "updated_at": "2024-01-20T14:22:00Z",
  "settings": {
    "timezone": "America/New_York",
    "date_format": "MM/DD/YYYY",
    "currency": "USD",
    "language": "en-US"
  },
  "subscription": {
    "plan": "enterprise",
    "status": "active",
    "expires_at": "2024-12-31T23:59:59Z",
    "features": [
      "advanced_analytics",
      "api_access",
      "custom_integrations",
      "priority_support"
    ]
  },
  "user_role": {
    "role": "admin",
    "permissions": [
      "manage_users",
      "manage_settings",
      "view_analytics",
      "manage_integrations"
    ],
    "joined_at": "2023-04-01T09:15:00Z"
  },
  "limits": {
    "max_users": 500,
    "current_users": 127,
    "max_api_calls": 10000,
    "current_api_calls": 2341
  },
  "branding": {
    "logo_url": "https://cdn.gate.zequenze.com/logos/acme-corp.png",
    "primary_color": "#0066CC",
    "secondary_color": "#F0F8FF"
  }
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns the user's organization information |
| 401 | Unauthorized - Invalid or missing authentication token |
| 403 | Forbidden - User does not have permission to view organization details |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error - Server encountered an error processing the request |

---

## Common Use Cases

### Use Case 1: Application Initialization
When a user logs into your application, call this endpoint to retrieve their organization context and configure the user interface with appropriate branding, settings, and available features based on their subscription plan.

### Use Case 2: Permission-Based Feature Access
Use the returned user role and permissions data to dynamically show or hide features in your application, ensuring users only see functionality they're authorized to access.

### Use Case 3: Organization Dashboard
Display organization statistics, current usage against limits, and subscription information in an admin dashboard or settings page.

### Use Case 4: Multi-Tenant Configuration
In multi-tenant applications, use the organization settings (timezone, currency, language) to customize the user experience and format data appropriately for each organization.

### Use Case 5: Subscription Management
Check the subscription status and available features to guide users toward appropriate upgrade paths or notify them of upcoming subscription renewals.

---

## Best Practices

- **Cache Organization Data**: Organization information changes infrequently, so cache the response for the duration of the user session to reduce API calls and improve performance.

- **Handle Permission Changes**: User permissions can be modified by organization administrators, so refresh organization data when users report access issues or after significant time periods.

- **Graceful Degradation**: Always handle cases where certain organization features or settings might be unavailable, and provide sensible defaults in your application.

- **Rate Limiting**: This endpoint is typically called once per session, but implement proper rate limiting and exponential backoff in case of errors to avoid hitting API limits.

- **Error Handling**: Implement robust error handling, especially for 403 errors which might indicate the user's access has been revoked or their organization status has changed.

- **Security Considerations**: Never expose sensitive organization information in client-side code or logs. Always validate user permissions server-side before performing privileged operations.

# Organization

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/organization/`](#get-organization) | <a href="https://gate.zequenze.com/api#/organization/organization_list" target="_blank">Swagger ↗</a> |

---
> The Organization API provides access to your organization hierarchy, allowing you to retrieve information about your primary organization and all sub-organizations you have access to. This endpoint is essential for understanding organizational structure, filtering data by organization, and building organization-aware applications.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Organization API enables developers to access organizational data within the GATE platform. Organizations in GATE represent hierarchical business entities that can contain sub-organizations, making it ideal for managing multi-location businesses, franchises, or enterprise divisions.

This API is particularly useful for:
- Building organization selectors in user interfaces
- Filtering other API data by organization
- Understanding organizational hierarchy and relationships
- Creating reports and analytics grouped by organization
- Managing multi-tenant applications where data access is organization-based

The endpoint returns paginated results and supports filtering by organization ID, name, and parent organization, making it flexible for various integration scenarios. Each organization includes metadata such as country, platform type, and hierarchical relationships through the parent organization structure.

---

## Endpoints

<a id="get-organization"></a>

### GET /organization/

**Description:** Retrieves a list of organizations that the authenticated user has access to, including their primary organization and any sub-organizations. This endpoint supports filtering and pagination, making it suitable for both complete organization lists and targeted searches.

**Use Cases:**
- Populating organization dropdown menus in applications
- Building organizational charts and hierarchy visualizations
- Filtering datasets by specific organizations
- Audit trails showing which organizations a user can access
- Multi-tenant application setup and organization-based routing

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/organization/?name=headquarters&is_active=true&limit=20&offset=0
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| id | string | query | No | Filter organizations by specific ID |
| name | string | query | No | Filter organizations by name (supports partial matching) |
| parent | string | query | No | Filter by parent organization ID to get sub-organizations |
| limit | integer | query | No | Number of results to return per page (default pagination applies) |
| offset | integer | query | No | The initial index from which to return results for pagination |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/organization/?limit=10&offset=0" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 25,
  "next": "https://gate.zequenze.com/api/v1/organization/?limit=10&offset=10",
  "previous": null,
  "results": [
    {
      "id": 1,
      "name": "Acme Corporation Headquarters",
      "short_name": "acme-hq",
      "is_active": true,
      "deleted": false,
      "country_code": "US",
      "platform": 1,
      "description": "Main headquarters for Acme Corporation",
      "parent": null,
      "parent_obj": null,
      "created": "2024-01-15T10:30:00Z"
    },
    {
      "id": 2,
      "name": "Acme West Coast Division",
      "short_name": "acme-west",
      "is_active": true,
      "deleted": false,
      "country_code": "US",
      "platform": 2,
      "description": "West Coast operations division",
      "parent": 1,
      "parent_obj": {
        "id": 1,
        "name": "Acme Corporation Headquarters",
        "short_name": "acme-hq",
        "is_active": true,
        "deleted": false,
        "country_code": "US",
        "platform": 1,
        "description": "Main headquarters for Acme Corporation",
        "parent": null,
        "created": "2024-01-15T10:30:00Z"
      },
      "created": "2024-02-01T14:20:00Z"
    },
    {
      "id": 3,
      "name": "Acme European Office",
      "short_name": "acme-eu",
      "is_active": true,
      "deleted": false,
      "country_code": "DE",
      "platform": 4,
      "description": "European operations center",
      "parent": 1,
      "parent_obj": {
        "id": 1,
        "name": "Acme Corporation Headquarters",
        "short_name": "acme-hq",
        "is_active": true,
        "deleted": false,
        "country_code": "US",
        "platform": 1,
        "description": "Main headquarters for Acme Corporation",
        "parent": null,
        "created": "2024-01-15T10:30:00Z"
      },
      "created": "2024-03-10T09:15:00Z"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated list of organizations |
| 401 | Unauthorized - Invalid or missing authentication token |
| 403 | Forbidden - User doesn't have permission to access organizations |
| 500 | Internal Server Error - Server-side error occurred |

---

## Common Use Cases

### Use Case 1: Building Organization Selector
Retrieve all active organizations to populate a dropdown menu in your application, allowing users to filter data or switch context between organizations.

```bash
https://gate.zequenze.com/api/v1/organization/?is_active=true&limit=100
```

### Use Case 2: Loading Sub-Organizations
Get all sub-organizations under a specific parent organization to build hierarchical views or organizational charts.

```bash
https://gate.zequenze.com/api/v1/organization/?parent=1&is_active=true
```

### Use Case 3: Organization Search
Search for organizations by name to implement organization lookup functionality in your application.

```bash
https://gate.zequenze.com/api/v1/organization/?name=west&limit=10
```

### Use Case 4: Paginated Organization List
Load organizations in batches for large datasets, implementing proper pagination in your user interface.

```bash
https://gate.zequenze.com/api/v1/organization/?limit=20&offset=40
```

### Use Case 5: Organization Validation
Verify if a specific organization exists and is accessible to the current user by filtering by ID.

```bash
https://gate.zequenze.com/api/v1/organization/?id=123
```

---

## Best Practices

- **Use pagination wisely**: Set appropriate `limit` values (10-50 items) to balance performance and user experience. Don't request all organizations at once if you have many.

- **Cache organization data**: Organization structures typically don't change frequently, so implement client-side caching to reduce API calls and improve application performance.

- **Handle hierarchy properly**: When working with parent-child relationships, use the `parent_obj` nested data to avoid additional API calls for parent organization details.

- **Filter inactive organizations**: In most user-facing scenarios, filter for `is_active=true` to hide deactivated organizations from users unless specifically managing organization status.

- **Implement proper error handling**: Always check for authentication errors (401) and handle cases where users might lose access to organizations due to permission changes.

- **Use short_name for URLs**: The `short_name` field is designed for use in URLs and identifiers - it's URL-safe and human-readable.

- **Respect platform values**: The `platform` field uses bitwise flags (1, 2, 4, 8, 16, 32, 64) - understand your platform requirements before filtering on this field.

---

# Portal Login

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `POST` | [`/portal_login/`](#post-portal_login) | <a href="https://gate.zequenze.com/api#/portal_login/portal_login_create" target="_blank">Swagger ↗</a> |

---
> The portal_login API provides functionality for managing captive portal authentication flows, allowing access points to redirect users through a centralized authentication system. This endpoint is primarily used in WiFi network environments where user authentication and session management are required before granting internet access.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The portal_login API category is designed for WiFi captive portal systems that need to authenticate users before granting network access. This API handles the critical handoff between access points, controllers, and the authentication platform.

**Key Concepts:**
- **Captive Portal Flow**: When users connect to WiFi, they're redirected to an authentication page before accessing the internet
- **Session Management**: The API creates authenticated sessions with configurable timeout periods
- **Multi-device Support**: Tracks individual devices by MAC address and assigns IP addresses
- **Controller Integration**: Works with network controllers to manage access point configurations

**Common Integration Scenarios:**
- Hotel WiFi systems requiring room number authentication
- Corporate guest networks with email-based login
- Public WiFi hotspots with terms of service acceptance
- Retail locations with social media login requirements

The portal_login endpoint serves as the authentication gateway, processing user credentials and device information to establish authorized network sessions.

---

## Endpoints

<a id="post-portal_login"></a>

### POST /portal_login/

**Description:** Executes a portal login operation to authenticate a user device and establish a network session. This endpoint processes authentication data from captive portals and creates authorized sessions with the network controller, enabling internet access for the authenticated device.

**Use Cases:**
- Authenticate hotel guests using room credentials before granting WiFi access
- Process corporate visitor registration and create temporary network access
- Handle social media login flows for public WiFi hotspots
- Validate terms of service acceptance for retail location WiFi

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/portal_login/
```

**Request Body Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| data | string | Yes | JSON string containing authentication and device information |

**Data Object Structure:**
The `data` parameter should contain a JSON string with the following authentication information:

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| uid | string | Yes | Unique identifier for the user (email, username, room number, etc.) |
| ap_mac | string | Yes | MAC address of the access point handling the connection |
| mac | string | Yes | MAC address of the user's device |
| ip | string | Yes | IP address assigned to the user's device |
| original_url | string | No | The original URL the user was trying to access |
| controller_address | string | No | IP address of the network controller |
| session_timeout | integer | No | Maximum session duration in seconds |
| idle_timeout | integer | No | Idle timeout period in seconds |

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/portal_login/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "data": "{\"uid\":\"guest@hotel.com\",\"ap_mac\":\"aa:bb:cc:dd:ee:ff\",\"mac\":\"11:22:33:44:55:66\",\"ip\":\"192.168.1.100\",\"original_url\":\"https://www.google.com\",\"controller_address\":\"192.168.1.1\",\"session_timeout\":3600,\"idle_timeout\":1800}"
  }'
```

**Example Request Body:**
```json
{
  "data": "{\"uid\":\"room_401\",\"ap_mac\":\"aa:bb:cc:dd:ee:ff\",\"mac\":\"11:22:33:44:55:66\",\"ip\":\"192.168.1.100\",\"original_url\":\"https://www.example.com\",\"controller_address\":\"192.168.1.1\",\"session_timeout\":7200,\"idle_timeout\":3600}"
}
```

**Example Response:**
```json
{
  "page_id": 12345,
  "original_url": "https://www.example.com",
  "ap_mac": "aa:bb:cc:dd:ee:ff",
  "mac": "11:22:33:44:55:66",
  "ip": "192.168.1.100",
  "uid": "room_401",
  "controller_address": "192.168.1.1",
  "session_timeout": 7200,
  "idle_timeout": 3600
}
```

**Response Fields:**

| Field | Type | Description |
|-------|------|-------------|
| page_id | integer | Unique identifier for this portal session |
| original_url | string | The URL the user was originally trying to access |
| ap_mac | string | MAC address of the access point |
| mac | string | MAC address of the authenticated device |
| ip | string | IP address assigned to the device |
| uid | string | User identifier used for authentication |
| controller_address | string | Network controller IP address |
| session_timeout | integer | Maximum session duration in seconds |
| idle_timeout | integer | Idle timeout duration in seconds |

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Success - Portal login completed successfully |
| 400 | Bad Request - Invalid data format or missing required fields |
| 401 | Unauthorized - Invalid or missing API token |
| 422 | Unprocessable Entity - Authentication failed or invalid user credentials |
| 500 | Internal Server Error - Server-side processing error |

---

## Common Use Cases

### Use Case 1: Hotel Guest Authentication
Authenticate hotel guests using their room number and last name. The portal captures the guest's device information and creates a session that expires at checkout time.

**Implementation:** Use the guest's room number as the `uid` and set `session_timeout` based on their stay duration.

### Use Case 2: Corporate Guest Network
Process visitor registration where guests provide their email address and accept terms of service before accessing the corporate guest WiFi.

**Implementation:** Use the guest's email as the `uid` and include the original destination URL to redirect them after authentication.

### Use Case 3: Public WiFi with Social Login
Handle authentication flows where users log in through social media platforms (Facebook, Google) to access free WiFi in retail locations.

**Implementation:** Use the social media user ID as the `uid` and set appropriate session timeouts for fair usage policies.

### Use Case 4: Event WiFi Management
Manage WiFi access for conference attendees using registration codes or badge scan data, with sessions that expire at the end of each day.

**Implementation:** Use attendee registration codes as the `uid` with daily session timeouts and controller integration for bandwidth management.

---

## Best Practices

**Data Format:**
- Always ensure the `data` parameter contains properly escaped JSON strings
- Validate MAC addresses are in the correct format (aa:bb:cc:dd:ee:ff) before sending
- Include session timeouts to prevent indefinite network access

**Error Handling:**
- Implement retry logic for temporary network failures (5xx errors)
- Validate user credentials before calling the API to minimize 422 responses
- Log authentication attempts for security monitoring and troubleshooting

**Security Considerations:**
- Never log or expose the full API token in client-side code
- Use HTTPS for all API communications to protect authentication data
- Implement rate limiting to prevent abuse of the authentication endpoint

**Performance Tips:**
- Cache successful authentication responses to avoid duplicate API calls
- Set appropriate session timeouts to balance user experience with resource usage
- Monitor API response times and implement timeout handling in your application

**Session Management:**
- Store the returned `page_id` for session tracking and potential logout operations
- Respect the configured timeout values and handle session expiration gracefully
- Consider implementing session renewal for long-term users

# Txlog Portal

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/txlog_portal/`](#get-txlog_portal) | <a href="https://gate.zequenze.com/api#/txlog_portal/txlog_portal_list" target="_blank">Swagger ↗</a> |

---
> The Portal Transaction Log API provides access to detailed transaction records from the Zequenze portal authentication system. This endpoint allows you to retrieve, filter, and analyze user authentication events, session activities, and system interactions for monitoring, auditing, and troubleshooting purposes.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The Portal Transaction Log API is designed for system administrators, security analysts, and developers who need to monitor and audit portal authentication activities. This API provides comprehensive access to transaction logs that capture every user interaction with the authentication portal, including logins, logouts, registrations, password changes, and various system events.

**Key Features:**
- **Comprehensive Transaction Types**: Track 26 different transaction types from user authentication to payment processing
- **Advanced Filtering**: Filter by date ranges, user, location, access point, and transaction type
- **Real-time Monitoring**: Access up-to-date transaction data for live monitoring dashboards
- **Audit Compliance**: Maintain detailed audit trails for security and compliance requirements
- **Troubleshooting Support**: Identify authentication issues and user experience problems

**Common Use Cases:**
- Security monitoring and intrusion detection
- User behavior analysis and session tracking
- Compliance reporting and audit trail generation
- System performance monitoring and troubleshooting
- Customer support and user assistance

The transaction logs include detailed metadata such as IP addresses, user agents, session IDs, location information, and status codes, providing a complete picture of portal activity.

---

## Endpoints

<a id="get-txlog_portal"></a>

### GET /txlog_portal/

**Description:** Retrieves a paginated list of portal transaction records with comprehensive filtering capabilities. This endpoint is essential for monitoring user authentication activities, analyzing login patterns, troubleshooting authentication issues, and generating audit reports. Each transaction record contains detailed information about user interactions with the portal authentication system.

**Use Cases:**
- Monitor failed authentication attempts for security analysis
- Generate compliance reports showing user access patterns
- Troubleshoot authentication issues by filtering specific user sessions
- Analyze portal usage statistics across different locations and access points
- Track registration and user management activities

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/txlog_portal/?type=ui&start_date=2024-01-01&end_date=2024-01-31&limit=50
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| type | string | query | No | Filter by transaction type. Use 'ui' for login, 'uo' for logout, 'ur' for registration, etc. |
| start_date | string | query | No | Start date for filtering (ISO format: 2024-01-01 or 2024-01-01T00:00:00Z) |
| end_date | string | query | No | End date for filtering (ISO format: 2024-01-31 or 2024-01-31T23:59:59Z) |
| user | integer | query | No | Filter transactions for a specific user ID |
| page | integer | query | No | Filter transactions from a specific page ID |
| access_point | integer | query | No | Filter by access point ID (WiFi hotspot, portal location) |
| location | integer | query | No | Filter by location ID (physical location or site) |
| cursor | string | query | No | Pagination cursor for efficient large dataset traversal |
| limit | integer | query | No | Number of results per page (default: 20, max: 100) |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/txlog_portal/?type=ui&start_date=2024-01-01&limit=25" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "next": "https://gate.zequenze.com/api/v1/txlog_portal/?cursor=eyJpZCI6MTAwfQ%3D%3D&limit=25",
  "previous": null,
  "results": [
    {
      "id": 12345,
      "datetime": "2024-01-15T14:30:25.123456Z",
      "type": "ui",
      "organization": 1,
      "source": "u",
      "status": "h200",
      "message": "User login successful",
      "service": 101,
      "service_name": "Corporate WiFi Portal",
      "authservice": 201,
      "authservice_name": "LDAP Authentication",
      "user": 5432,
      "username": "john.doe",
      "email": "john.doe@company.com",
      "external_id": "emp_12345",
      "new_user": false,
      "session_id": "sess_abc123xyz789",
      "external_session": "ldap_session_456",
      "payment_transaction_log": null,
      "site": "corporate-portal.company.com",
      "page": 10,
      "page_url": "https://corporate-portal.company.com/login",
      "action": "li",
      "location": 15,
      "location_name": "Headquarters Building A",
      "access_point": 42,
      "access_point_name": "AP-Floor3-West",
      "ssid": "Corporate_WiFi",
      "user_agent": 301,
      "remote_ip_addr": 987654321,
      "captured_ip_addr": 987654321,
      "mac_addr": 123456789,
      "http_referer": 501
    },
    {
      "id": 12344,
      "datetime": "2024-01-15T14:28:15.789012Z",
      "type": "ur",
      "organization": 1,
      "source": "u",
      "status": "h201",
      "message": "User registration completed",
      "service": 101,
      "service_name": "Corporate WiFi Portal",
      "authservice": null,
      "authservice_name": null,
      "user": 5433,
      "username": "jane.smith",
      "email": "jane.smith@company.com",
      "external_id": null,
      "new_user": true,
      "session_id": "sess_def456uvw012",
      "external_session": null,
      "payment_transaction_log": null,
      "site": "corporate-portal.company.com",
      "page": 12,
      "page_url": "https://corporate-portal.company.com/register",
      "action": "rg",
      "location": 15,
      "location_name": "Headquarters Building A",
      "access_point": 43,
      "access_point_name": "AP-Floor2-East",
      "ssid": "Guest_WiFi",
      "user_agent": 302,
      "remote_ip_addr": 987654322,
      "captured_ip_addr": 987654322,
      "mac_addr": 123456790,
      "http_referer": 502
    }
  ]
}
```

**Transaction Types Reference:**

| Code | Description | Use Case |
|------|-------------|----------|
| ua | Authenticate | Initial authentication attempts |
| ui | Login | Successful user logins |
| ue | Re-authenticate | Session re-authentication |
| uo | Logout | User logout events |
| uc | User capture | Data capture during registration |
| ur | User registration | New user account creation |
| uu | User update | Profile or account updates |
| un | User activation | Account activation events |
| up | Password change | Password modification |
| um | User activated API | API-triggered user activation |
| ai | Auto-login | Automatic login processes |
| aa | Auto-authenticate | Automatic authentication |
| st | Session timeout | Session expiration events |
| si | Idle timeout | Idle session termination |
| di | Disconnect | Manual or forced disconnections |

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns filtered transaction records |
| 400 | Bad Request - Invalid filter parameters or date format |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions to access transaction logs |
| 429 | Too Many Requests - Rate limit exceeded |

---

## Common Use Cases

### Use Case 1: Security Monitoring Dashboard
Monitor failed authentication attempts and suspicious login patterns by filtering for specific status codes and authentication types.

```bash
# Get failed login attempts in the last 24 hours
curl -X GET "https://gate.zequenze.com/api/v1/txlog_portal/?type=ui&status=u401&start_date=2024-01-15T00:00:00Z&end_date=2024-01-15T23:59:59Z" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

### Use Case 2: User Session Analysis
Track a specific user's authentication journey by filtering their transactions across different session activities.

```bash
# Get all transactions for user ID 5432 in January 2024
curl -X GET "https://gate.zequenze.com/api/v1/txlog_portal/?user=5432&start_date=2024-01-01&end_date=2024-01-31" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

### Use Case 3: Location-Based Usage Reports
Generate usage statistics for specific locations or access points to understand traffic patterns and capacity planning.

```bash
# Get all transactions from a specific access point
curl -X GET "https://gate.zequenze.com/api/v1/txlog_portal/?access_point=42&start_date=2024-01-01&limit=100" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

### Use Case 4: Registration and User Management Audit
Track user registration activities and account management operations for compliance reporting.

```bash
# Get all registration-related transactions
curl -X GET "https://gate.zequenze.com/api/v1/txlog_portal/?type=ur,uu,un&start_date=2024-01-01&end_date=2024-01-31" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

### Use Case 5: Payment Transaction Monitoring
Monitor payment-related portal activities for e-commerce or paid access scenarios.

```bash
# Get payment process transactions
curl -X GET "https://gate.zequenze.com/api/v1/txlog_portal/?type=pp&start_date=2024-01-01" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

---

## Best Practices

- **Use Date Filtering**: Always apply date ranges to limit result sets and improve query performance. Large unbounded queries may timeout or hit rate limits.

- **Implement Pagination**: Use the cursor-based pagination for large datasets rather than requesting all records at once. The cursor parameter provides better performance than offset-based pagination.

- **Cache Common Queries**: Cache frequently accessed data like daily statistics or user lookup results to reduce API calls and improve application performance.

- **Monitor Rate Limits**: Transaction log endpoints may have strict rate limits. Implement exponential backoff and respect HTTP 429 responses.

- **Secure Token Storage**: Store API tokens securely and rotate them regularly. Transaction logs contain sensitive user information and require proper authentication.

- **Filter Efficiently**: Use specific filters (type, user, location) to reduce payload size and improve response times. Avoid broad queries during peak hours.

- **Error Handling**: Implement robust error handling for network timeouts, API errors, and malformed responses. Transaction logs are critical for security monitoring.

- **Data Retention Awareness**: Understand your organization's log retention policies. Historical data may not be available beyond certain time periods.

---

# User

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/user/`](#get-user) | <a href="https://gate.zequenze.com/api#/user/user_list" target="_blank">Swagger ↗</a> |
| `POST` | [`/user/`](#post-user) | <a href="https://gate.zequenze.com/api#/user/user_create" target="_blank">Swagger ↗</a> |
| `GET` | [`/user/username/{username}/`](#get-user-username-username) | <a href="https://gate.zequenze.com/api#/user/user_username_read" target="_blank">Swagger ↗</a> |
| `PUT` | [`/user/username/{username}/`](#put-user-username-username) | <a href="https://gate.zequenze.com/api#/user/user_username_update" target="_blank">Swagger ↗</a> |
| `PATCH` | [`/user/username/{username}/`](#patch-user-username-username) | <a href="https://gate.zequenze.com/api#/user/user_username_partial_update" target="_blank">Swagger ↗</a> |
| `DELETE` | [`/user/username/{username}/`](#delete-user-username-username) | <a href="https://gate.zequenze.com/api#/user/user_username_delete" target="_blank">Swagger ↗</a> |
| `GET` | [`/user/{id}/`](#get-user-id) | <a href="https://gate.zequenze.com/api#/user/user_read" target="_blank">Swagger ↗</a> |
| `PUT` | [`/user/{id}/`](#put-user-id) | <a href="https://gate.zequenze.com/api#/user/user_update" target="_blank">Swagger ↗</a> |
| `PATCH` | [`/user/{id}/`](#patch-user-id) | <a href="https://gate.zequenze.com/api#/user/user_partial_update" target="_blank">Swagger ↗</a> |
| `DELETE` | [`/user/{id}/`](#delete-user-id) | <a href="https://gate.zequenze.com/api#/user/user_delete" target="_blank">Swagger ↗</a> |

---
> The User API endpoints provide comprehensive user management capabilities including authentication, authorization, and access control (AAA) profile management. These endpoints allow you to create, retrieve, update, and delete users in your system, manage their profiles and permissions, and handle user lifecycle operations like account expiration and status management.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The User API is the core component for managing user accounts and their associated AAA (Authentication, Authorization, and Accounting) profiles within the GATE system. This API provides full CRUD operations for user management, allowing you to integrate user provisioning, profile management, and access control into your applications.

**Key Features:**
- **User Lifecycle Management**: Create, read, update, and delete user accounts with comprehensive profile information
- **AAA Profile Integration**: Assign and manage Authentication, Authorization, and Accounting profiles for fine-grained access control
- **Flexible User Identification**: Support for both internal ID-based operations and username-based operations for easier integration
- **External System Integration**: Built-in support for external IDs and service class references to link users with external systems
- **Account Management**: Handle user expiration dates, activation status, and login tracking
- **Organization Support**: Associate users with specific organizations for multi-tenant environments

**Common Integration Scenarios:**
- **Identity Provider Integration**: Sync users from LDAP, Active Directory, or other identity systems
- **Application User Management**: Provision users for web applications, network services, or cloud resources
- **Automated Onboarding**: Create user accounts as part of employee onboarding workflows
- **Access Control Management**: Assign and modify user permissions through AAA profile assignments
- **User Analytics**: Track user login patterns and account lifecycle for reporting and compliance

The API supports both paginated listing of users with flexible filtering options and individual user operations, making it suitable for both bulk operations and real-time user management tasks.

---

## Endpoints

<a id="get-user"></a>

### GET /user/

**Description:** Retrieves a paginated list of all users in the system, including their AAA profile assignments and comprehensive user information. This endpoint supports flexible filtering by user ID, username, or organization, making it ideal for user search functionality, bulk operations, and administrative dashboards.

**Use Cases:**
- Building user management interfaces with search and filtering capabilities
- Synchronizing user data between systems
- Generating user reports and analytics
- Bulk user operations and auditing

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/?username=john.doe&organization=1&limit=50&offset=0
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| id | string | query | No | Filter users by specific user ID |
| username | string | query | No | Filter users by username (supports partial matching) |
| organization | string | query | No | Filter users by organization ID |
| limit | integer | query | No | Number of results to return per page (default: 20, max: 100) |
| offset | integer | query | No | The initial index from which to return the results for pagination |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/user/?organization=1&limit=25&offset=0" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 150,
  "next": "https://gate.zequenze.com/api/v1/user/?limit=25&offset=25",
  "previous": null,
  "results": [
    {
      "id": 1,
      "username": "john.doe",
      "external_id": "EMP001234",
      "klass": "standard_employee",
      "email": "john.doe@company.com",
      "first_name": "John",
      "last_name": "Doe",
      "is_active": true,
      "organization": 1,
      "description": "Senior Network Engineer",
      "date_joined": "2024-01-15T10:30:00Z",
      "first_login": "2024-01-16T08:15:00Z",
      "last_login": "2024-03-20T14:22:00Z",
      "expiration": "2025-01-15T23:59:59Z",
      "avatar_url": "https://gate.zequenze.com/avatars/john.doe.jpg",
      "source_id": 1,
      "profile": ["network_admin", "vpn_user", "wifi_access"]
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated list of users |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions to list users |

---

<a id="post-user"></a>

### POST /user/

**Description:** Creates a new user account with optional AAA profile assignments. This endpoint allows you to provision new users with comprehensive profile information, external system references, and initial access permissions. The username is the only required field, with all other user attributes being optional.

**Use Cases:**
- User onboarding and account provisioning workflows
- Automated user creation from HR systems or identity providers
- Self-service account registration processes
- Bulk user import operations

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/
```

**Request Body Schema:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| username | string | Yes | Unique username (150 chars max, letters, digits, @/./+/-/:/ |/_ only) |
| password | string | No | User password (will be hashed) |
| email | string | No | Valid email address |
| first_name | string | No | User's first name |
| last_name | string | No | User's last name |
| external_id | string | No | Reference ID for external systems |
| klass | string | No | Service class identifier |
| is_active | boolean | No | Account active status (default: true) |
| organization | integer | No | Organization ID to associate user with |
| description | string | No | Additional user description or notes |
| expiration | string | No | Account expiration date (ISO 8601 format) |
| avatar_url | string | No | URL to user's avatar image |
| profile | array | No | List of AAA profile short-names to assign |

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/user/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "jane.smith",
    "email": "jane.smith@company.com",
    "first_name": "Jane",
    "last_name": "Smith",
    "password": "SecurePassword123!",
    "external_id": "EMP005678",
    "organization": 1,
    "description": "Software Developer",
    "expiration": "2025-12-31T23:59:59Z",
    "profile": ["developer_access", "vpn_user"]
  }'
```

**Example Response:**
```json
{
  "id": 42,
  "username": "jane.smith",
  "external_id": "EMP005678",
  "klass": null,
  "email": "jane.smith@company.com",
  "first_name": "Jane",
  "last_name": "Smith",
  "is_active": true,
  "organization": 1,
  "description": "Software Developer",
  "date_joined": "2024-03-21T10:30:00Z",
  "first_login": null,
  "last_login": null,
  "expiration": "2025-12-31T23:59:59Z",
  "avatar_url": null,
  "profile": ["developer_access", "vpn_user"]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - User successfully created |
| 400 | Bad Request - Invalid data or validation errors |
| 401 | Unauthorized - Invalid or missing API token |
| 409 | Conflict - Username already exists |

---

<a id="get-user-username-username"></a>

### GET /user/username/{username}/

**Description:** Retrieves detailed information for a specific user identified by their username. This endpoint is particularly useful when you know the username but not the internal user ID, making it ideal for user lookup operations and profile management interfaces.

**Use Cases:**
- User profile lookups in applications
- Username-based authentication flows
- User information display in administrative interfaces
- Integration with systems that use usernames as primary identifiers

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/username/john.doe/
```

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/user/username/john.doe/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "id": 1,
  "username": "john.doe",
  "external_id": "EMP001234",
  "klass": "standard_employee",
  "email": "john.doe@company.com",
  "first_name": "John",
  "last_name": "Doe",
  "is_active": true,
  "organization": 1,
  "description": "Senior Network Engineer",
  "date_joined": "2024-01-15T10:30:00Z",
  "first_login": "2024-01-16T08:15:00Z",
  "last_login": "2024-03-20T14:22:00Z",
  "expiration": "2025-01-15T23:59:59Z",
  "avatar_url": "https://gate.zequenze.com/avatars/john.doe.jpg",
  "source_id": 1,
  "profile": ["network_admin", "vpn_user", "wifi_access"]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns user information |
| 401 | Unauthorized - Invalid or missing API token |
| 404 | Not Found - Username does not exist |

---

<a id="put-user-username-username"></a>

### PUT /user/username/{username}/

**Description:** Completely replaces all user information for the specified username. This endpoint performs a full update, requiring all fields to be provided as it will overwrite the existing user record entirely. Use PATCH for partial updates instead.

**Use Cases:**
- Complete user profile synchronization from external systems
- User migration between systems with full data replacement
- Administrative bulk user updates where all fields are known

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/username/john.doe/
```

**cURL Example:**
```bash
curl -X PUT "https://gate.zequenze.com/api/v1/user/username/john.doe/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john.doe",
    "email": "john.doe@newcompany.com",
    "first_name": "John",
    "last_name": "Doe-Smith",
    "external_id": "EMP001234",
    "klass": "senior_employee",
    "is_active": true,
    "organization": 2,
    "description": "Principal Network Architect",
    "expiration": "2026-01-15T23:59:59Z",
    "profile": ["network_admin", "infrastructure_admin", "vpn_user"]
  }'
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - User successfully updated |
| 400 | Bad Request - Invalid data or validation errors |
| 401 | Unauthorized - Invalid or missing API token |
| 404 | Not Found - Username does not exist |

---

<a id="patch-user-username-username"></a>

### PATCH /user/username/{username}/

**Description:** Performs a partial update of user information for the specified username. Only the fields provided in the request body will be updated, leaving all other user attributes unchanged. This is the preferred method for making specific changes to user accounts.

**Use Cases:**
- Updating specific user attributes like email or organization
- Modifying AAA profile assignments
- Activating or deactivating user accounts
- Extending or modifying user expiration dates

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/username/john.doe/
```

**cURL Example:**
```bash
curl -X PATCH "https://gate.zequenze.com/api/v1/user/username/john.doe/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john.doe@updated-email.com",
    "organization": 3,
    "profile": ["network_admin", "vpn_user", "new_access_profile"]
  }'
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - User successfully updated |
| 400 | Bad Request - Invalid data or validation errors |
| 401 | Unauthorized - Invalid or missing API token |
| 404 | Not Found - Username does not exist |

---

<a id="delete-user-username-username"></a>

### DELETE /user/username/{username}/

**Description:** Permanently deletes the user account identified by the specified username. This operation cannot be undone and will remove all user data, including AAA profile assignments and historical login information.

**Use Cases:**
- User offboarding and account cleanup
- Removing test accounts or invalid user records
- Compliance-driven account deletion requirements
- Automated account lifecycle management

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/username/john.doe/
```

**cURL Example:**
```bash
curl -X DELETE "https://gate.zequenze.com/api/v1/user/username/john.doe/" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 204 | No Content - User successfully deleted |
| 401 | Unauthorized - Invalid or missing API token |
| 404 | Not Found - Username does not exist |

---

<a id="get-user-id"></a>

### GET /user/{id}/

**Description:** Retrieves detailed information for a specific user identified by their internal user ID. This endpoint provides the same functionality as the username-based lookup but uses the system's internal ID as the identifier.

**Use Cases:**
- Retrieving user information when you have the internal ID
- Following references from other API responses that include user IDs
- Building relationships between users and other system entities

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/42/
```

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/user/42/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns user information |
| 401 | Unauthorized - Invalid or missing API token |
| 404 | Not Found - User ID does not exist |

---

<a id="put-user-id"></a>

### PUT /user/{id}/

**Description:** Completely replaces all user information for the specified user ID. This endpoint performs a full update, requiring all fields to be provided as it will overwrite the existing user record entirely.

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/42/
```

**cURL Example:**
```bash
curl -X PUT "https://gate.zequenze.com/api/v1/user/42/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "jane.smith",
    "email": "jane.smith@company.com",
    "first_name": "Jane",
    "last_name": "Smith-Johnson",
    "is_active": true,
    "organization": 1,
    "profile": ["developer_access", "admin_access"]
  }'
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - User successfully updated |
| 400 | Bad Request - Invalid data or validation errors |
| 401 | Unauthorized - Invalid or missing API token |
| 404 | Not Found - User ID does not exist |

---

<a id="patch-user-id"></a>

### PATCH /user/{id}/

**Description:** Performs a partial update of user information for the specified user ID. Only the fields provided in the request body will be updated, making this ideal for targeted modifications to user accounts.

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/42/
```

**cURL Example:**
```bash
curl -X PATCH "https://gate.zequenze.com/api/v1/user/42/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "is_active": false,
    "description": "Account suspended pending review"
  }'
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - User successfully updated |
| 400 | Bad Request - Invalid data or validation errors |
| 401 | Unauthorized - Invalid or missing API token |
| 404 | Not Found - User ID does not exist |

---

<a id="delete-user-id"></a>

### DELETE /user/{id}/

**Description:** Permanently deletes the user account identified by the specified user ID. This operation cannot be undone and will remove all user data and associated relationships.

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user/42/
```

**cURL Example:**
```bash
curl -X DELETE "https://gate.zequenze.com/api/v1/user/42/" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 204 | No Content - User successfully deleted |
| 401 | Unauthorized - Invalid or missing API token |
| 404 | Not Found - User ID does not exist |

---

## Common Use Cases

### Use Case 1: Employee Onboarding Workflow
When a new employee joins your organization, you can automate their account creation and access provisioning using POST /user/ to create the account with appropriate AAA profiles, then use PATCH operations to update their information as they progress through onboarding stages.

### Use Case 2: Directory Synchronization
For organizations using external identity providers, use GET /user/ with filtering to retrieve current users, compare with your external directory, then use POST to create new users and PATCH to update existing ones, ensuring your GATE system stays synchronized.

### Use Case 3: Access Management and Compliance
Use GET /user/ to generate reports on user access and expiration dates, then use PATCH operations to update user profiles, modify expiration dates, or deactivate accounts that no longer require access, maintaining compliance with security policies.

### Use Case 4: Self-Service Profile Management
Build user portals where users can view their information using GET /user/username/{username}/ and submit profile updates that your system processes using PATCH /user/username/{username}/ after appropriate approval workflows.

### Use Case 5: Account Lifecycle Automation
Implement automated processes that monitor user activity and account status, using PATCH operations to extend expiration dates for active users, deactivate dormant accounts, or DELETE accounts that are no longer needed based on your organization's retention policies.

---

## Best Practices

- **Use Pagination Effectively**: When listing users, always implement proper pagination using limit and offset parameters to avoid performance issues with large user datasets. Start with reasonable page sizes (25-50 users) and adjust based on your application's needs.

- **Leverage Username-Based Operations**: For user-facing applications, prefer the username-based endpoints (/user/username/{username}/) as they're more intuitive and don't expose internal system IDs. Reserve ID-based operations for internal system integrations.

- **Implement Proper Error Handling**: Always check response codes and handle common scenarios like 404 (user not found), 409 (username conflicts), and 401 (authentication failures) gracefully in your applications.

- **Manage AAA Profiles Carefully**: When updating user profiles, retrieve the current profile list first to avoid accidentally removing necessary access permissions. Consider implementing approval workflows for profile changes that grant additional access.

- **Use Partial Updates**: Prefer PATCH over PUT operations to avoid accidentally clearing user data. PATCH operations are safer and more efficient as they only modify the specified fields.

- **Monitor Account Expiration**: Implement monitoring for user expiration dates and automate extension or notification processes. Users with expired accounts may lose access unexpectedly if not properly managed.

- **Secure Sensitive Operations**: Implement additional validation and approval processes for sensitive operations like user deletion or profile modifications that grant administrative access.

- **Cache User Information Wisely**: Consider caching user information for frequently accessed data, but ensure cache invalidation strategies are in place for when user information changes, especially for authentication and authorization data.

---

# User Extra

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/user_extra/`](#get-user_extra) | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_list" target="_blank">Swagger ↗</a> |
| `POST` | [`/user_extra/`](#post-user_extra) | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_create" target="_blank">Swagger ↗</a> |
| `GET` | [`/user_extra/{id}/`](#get-user_extra-id) | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_read" target="_blank">Swagger ↗</a> |
| `PUT` | [`/user_extra/{id}/`](#put-user_extra-id) | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_update" target="_blank">Swagger ↗</a> |
| `PATCH` | [`/user_extra/{id}/`](#patch-user_extra-id) | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_partial_update" target="_blank">Swagger ↗</a> |
| `DELETE` | [`/user_extra/{id}/`](#delete-user_extra-id) | <a href="https://gate.zequenze.com/api#/user_extra/user_extra_delete" target="_blank">Swagger ↗</a> |

---
> The User Extra API provides endpoints for managing extended user profile information beyond basic authentication details. These endpoints allow you to store and retrieve additional user attributes such as contact information, demographics, custom fields, and location data, enabling rich user profiles for your GATE-integrated applications.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The User Extra API category enables you to manage supplementary user information that extends beyond the core user authentication data. This API is essential for applications that need to collect and maintain detailed user profiles, including personal information, contact details, demographic data, and custom business-specific fields.

**Key Features:**
- **Extended Profile Management**: Store up to 8 custom fields plus standard demographic and contact information
- **Flexible Data Storage**: Support for various data types including dates, strings, integers, and enumerations
- **Parent-Child Relationships**: Link extra information to parent user accounts and filter by organization
- **Device Information**: Optional inclusion of device-related data for enhanced user tracking
- **Full CRUD Operations**: Complete create, read, update, and delete capabilities

**Common Use Cases:**
- Building comprehensive user registration forms with extended profile fields
- Collecting demographic data for analytics and reporting
- Managing customer contact information for support and communication
- Storing event-specific attendee information
- Maintaining custom business fields specific to your organization's needs
- Tracking user preferences and locale settings

**Data Model:**
The User Extra resource connects to a parent user account and can store personal details (name, birthday, gender), location information (address, city, country, postal code), contact details (telephone, email preferences), business information (company, tax ID, passport number), and flexible custom fields for organization-specific data.

---

## Endpoints

<a id="get-user_extra"></a>

### GET /user_extra/

**Description:** Retrieves a paginated list of user extra information records. This endpoint supports filtering by parent user, organization, and includes optional device information. Use this endpoint to browse all extended user profiles, filter by specific users or organizations, or retrieve bulk user data for reporting and analytics.

**Use Cases:**
- Retrieve all user profiles within a specific organization for reporting
- Search for users with specific parent relationships
- Export extended user data for analytics or data migration
- Build user directories with detailed profile information

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_extra/?parent__organization_id=123&limit=50&offset=0&device_info=true
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| parent | string | query | No | Filter by parent user ID. Returns only user extra records linked to the specified parent user. |
| parent__organization_id | string | query | No | Filter by organization ID. Returns user extra records where the parent user belongs to the specified organization. |
| limit | integer | query | No | Number of results to return per page. Default is typically 10-100 depending on server configuration. Use for pagination control. |
| offset | integer | query | No | The initial index from which to return results. Use with limit for pagination (e.g., offset=20&limit=10 returns records 21-30). |
| device_info | boolean | query | No | When set to true, includes device information associated with the user extra records in the response. |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/user_extra/?parent__organization_id=456&limit=25&offset=0" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 150,
  "next": "https://gate.zequenze.com/api/v1/user_extra/?limit=25&offset=25&parent__organization_id=456",
  "previous": null,
  "results": [
    {
      "id": 1,
      "parent": 42,
      "title": "Dr.",
      "gender": "f",
      "birthday": "1985-06-15",
      "age": 38,
      "age_range": "35-44",
      "telephone": "+1-555-0123",
      "address": "123 Main Street",
      "city": "San Francisco",
      "state": "CA",
      "postal_code": "94102",
      "country": "United States",
      "country_id": "US",
      "company": "Tech Solutions Inc",
      "tax_id": "123-45-6789",
      "passport_number": null,
      "hometown": "Seattle",
      "location": "San Francisco, CA",
      "locale": "en_US",
      "event": "TechConf 2024",
      "accept_terms": true,
      "custom_field_1": "Premium Member",
      "custom_field_2": "Referral: LinkedIn",
      "custom_field_3": null,
      "custom_field_4": null,
      "custom_field_5": null,
      "custom_field_6": null,
      "custom_field_7": null,
      "custom_field_8": null
    },
    {
      "id": 2,
      "parent": 43,
      "title": "Mr.",
      "gender": "m",
      "birthday": "1990-03-22",
      "age": 33,
      "age_range": "30-34",
      "telephone": "+1-555-0456",
      "address": "456 Oak Avenue",
      "city": "Austin",
      "state": "TX",
      "postal_code": "78701",
      "country": "United States",
      "country_id": "US",
      "company": "Startup Ventures LLC",
      "tax_id": "987-65-4321",
      "passport_number": "X12345678",
      "hometown": "Houston",
      "location": "Austin, TX",
      "locale": "en_US",
      "event": "TechConf 2024",
      "accept_terms": true,
      "custom_field_1": "Standard Member",
      "custom_field_2": "Referral: Website",
      "custom_field_3": "VIP Access",
      "custom_field_4": null,
      "custom_field_5": null,
      "custom_field_6": null,
      "custom_field_7": null,
      "custom_field_8": null
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated list of user extra records |
| 401 | Unauthorized - Invalid or missing authentication token |
| 403 | Forbidden - Authenticated user lacks permission to view these records |
| 400 | Bad Request - Invalid query parameters provided |

---

<a id="post-user_extra"></a>

### POST /user_extra/

**Description:** Creates a new user extra information record. This endpoint allows you to add extended profile information for a user by linking it to a parent user ID. All fields except the parent ID are optional, providing flexibility to collect only the information relevant to your application. Use this when onboarding new users or collecting additional profile information.

**Use Cases:**
- Complete user registration by adding extended profile information after account creation
- Collect attendee information during event registration
- Add demographic and contact details for marketing segmentation
- Store custom business-specific fields during user onboarding

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_extra/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| data | object | body | Yes | JSON object containing the user extra information fields. Only the `parent` field is required. |

**Request Body Schema:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| parent | integer | Yes | The ID of the parent user account this extra information belongs to |
| title | string | No | User's title or honorific (e.g., Dr., Mr., Ms., Prof.) |
| gender | string | No | User's gender. Allowed values: "m" (male), "f" (female), "o" (other) |
| birthday | string | No | User's date of birth in YYYY-MM-DD format |
| age | integer | No | User's age in years |
| age_range | string | No | Age range category (e.g., "25-34", "35-44") |
| telephone | string | No | User's telephone number |
| address | string | No | Street address |
| city | string | No | City name |
| state | string | No | State or province |
| postal_code | string | No | Postal or ZIP code |
| country | string | No | Country name |
| country_id | string | No | ISO country code (e.g., "US", "GB", "DE") |
| company | string | No | Company or organization name |
| tax_id | string | No | Tax identification number |
| passport_number | string | No | Passport number |
| hometown | string | No | User's hometown |
| location | string | No | Current location description |
| locale | string | No | Locale/language preference (e.g., "en_US", "es_ES") |
| event | string | No | Associated event name or identifier |
| accept_terms | boolean | No | Whether user has accepted terms and conditions |
| custom_field_1 to custom_field_8 | string | No | Flexible custom fields for organization-specific data |

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/user_extra/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "parent": 42,
    "title": "Ms.",
    "gender": "f",
    "birthday": "1992-08-14",
    "telephone": "+1-555-0789",
    "address": "789 Pine Street",
    "city": "Portland",
    "state": "OR",
    "postal_code": "97201",
    "country": "United States",
    "country_id": "US",
    "company": "Creative Agency Co",
    "locale": "en_US",
    "accept_terms": true,
    "custom_field_1": "Gold Tier",
    "custom_field_2": "Newsletter: Yes"
  }'
```

**Example Response:**
```json
{
  "id": 125,
  "parent": 42,
  "title": "Ms.",
  "gender": "f",
  "birthday": "1992-08-14",
  "age": null,
  "age_range": null,
  "telephone": "+1-555-0789",
  "address": "789 Pine Street",
  "city": "Portland",
  "state": "OR",
  "postal_code": "97201",
  "country": "United States",
  "country_id": "US",
  "company": "Creative Agency Co",
  "tax_id": null,
  "passport_number": null,
  "hometown": null,
  "location": null,
  "locale": "en_US",
  "event": null,
  "accept_terms": true,
  "custom_field_1": "Gold Tier",
  "custom_field_2": "Newsletter: Yes",
  "custom_field_3": null,
  "custom_field_4": null,
  "custom_field_5": null,
  "custom_field_6": null,
  "custom_field_7": null,
  "custom_field_8": null
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - User extra record successfully created |
| 400 | Bad Request - Invalid data provided (e.g., missing parent ID, invalid date format, invalid gender value) |
| 401 | Unauthorized - Invalid or missing authentication token |
| 403 | Forbidden - User lacks permission to create user extra records |
| 404 | Not Found - Parent user ID does not exist |

---

<a id="get-user_extra-id"></a>

### GET /user_extra/{id}/

**Description:** Retrieves a specific user extra information record by its unique ID. This endpoint returns all stored extended profile information for a single user, optionally including device information. Use this to display user profile details, verify stored information, or retrieve data for editing.

**Use Cases:**
- Display complete user profile information on a user details page
- Retrieve user data before updating to show current values in an edit form
- Verify user information for customer support or verification purposes
- Fetch user demographics for personalized content delivery

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_extra/125/?device_info=true
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| id | integer | path | Yes | The unique identifier of the user extra record to retrieve |
| device_info | boolean | query | No | When set to true, includes device information associated with this user extra record |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/user_extra/125/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "id": 125,
  "parent": 42,
  "title": "Ms.",
  "gender": "f",
  "birthday": "1992-08-14",
  "age": 31,
  "age_range": "30-34",
  "telephone": "+1-555-0789",
  "address": "789 Pine Street",
  "city": "Portland",
  "state": "OR",
  "postal_code": "97201",
  "country": "United States",
  "country_id": "US",
  "company": "Creative Agency Co",
  "tax_id": "555-66-7777",
  "passport_number": null,
  "hometown": "Eugene",
  "location": "Portland, OR",
  "locale": "en_US",
  "event": "Design Summit 2024",
  "accept_terms": true,
  "custom_field_1": "Gold Tier",
  "custom_field_2": "Newsletter: Yes",
  "custom_field_3": "Preferred contact: Email",
  "custom_field_4": null,
  "custom_field_5": null,
  "custom_field_6": null,
  "custom_field_7": null,
  "custom_field_8": null
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns the requested user extra record |
| 401 | Unauthorized - Invalid or missing authentication token |
| 403 | Forbidden - User lacks permission to view this record |
| 404 | Not Found - User extra record with specified ID does not exist |

---

<a id="put-user_extra-id"></a>

### PUT /user_extra/{id}/

**Description:** Completely replaces an existing user extra information record with new data. This endpoint requires all fields to be provided, effectively performing a full update. Any fields not included in the request will be cleared (set to null). Use PUT when you want to completely replace the user's extra information or when you have a complete data set to update.

**Use Cases:**
- Completely refresh user profile data from an external source
- Implement a "replace all" profile update functionality
- Synchronize complete user records from another system
- Reset user profile to a known state

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_extra/125/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| id | integer | path | Yes | The unique identifier of the user extra record to update |
| data | object | body | Yes | Complete JSON object containing all user extra information fields |

**Request Body Schema:**
Same as POST endpoint - all fields should be provided to avoid clearing existing data.

**cURL Example:**
```bash
curl -X PUT "https://gate.zequenze.com/api/v1/user_extra/125/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "parent": 42,
    "title": "Dr.",
    "gender": "f",
    "birthday": "1992-08-14",
    "age": 31,
    "age_range": "30-34",
    "telephone": "+1-555-0999",
    "address": "789 Pine Street, Apt 4B",
    "city": "Portland",
    "state": "OR",
    "postal_code": "97201",
    "country": "United States",
    "country_id": "US",
    "company": "Creative Agency Co",
    "tax_id": "555-66-7777",
    "passport_number": null,
    "hometown": "Eugene",
    "location": "Portland, OR",
    "locale": "en_US",
    "event": "Design Summit 2024",
    "accept_terms": true,
    "custom_field_1": "Platinum Tier",
    "custom_field_2": "Newsletter: Yes",
    "custom_field_3": "Preferred contact: Phone",
    "custom_field_4": "Emergency contact: Jane Doe",
    "custom_field_5": null,
    "custom_field_6": null,
    "custom_field_7": null,
    "custom_field_8": null
  }'
```

**Example Response:**
```json
{
  "id": 125,
  "parent": 42,
  "title": "Dr.",
  "gender": "f",
  "birthday": "1992-08-14",
  "age": 31,
  "age_range": "30-34",
  "telephone": "+1-555-0999",
  "address": "789 Pine Street, Apt 4B",
  "city": "Portland",
  "state": "OR",
  "postal_code": "97201",
  "country": "United States",
  "country_id": "US",
  "company": "Creative Agency Co",
  "tax_id": "555-66-7777",
  "passport_number": null,
  "hometown": "Eugene",
  "location": "Portland, OR",
  "locale": "en_US",
  "event": "Design Summit 2024",
  "accept_terms": true,
  "custom_field_1": "Platinum Tier",
  "custom_field_2": "Newsletter: Yes",
  "custom_field_3": "Preferred contact: Phone",
  "custom_field_4": "Emergency contact: Jane Doe",
  "custom_field_5": null,
  "custom_field_6": null,
  "custom_field_7": null,
  "custom_field_8": null
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - User extra record successfully updated |
| 400 | Bad Request - Invalid data provided (e.g., invalid date format, invalid gender value) |
| 401 | Unauthorized - Invalid or missing authentication token |
| 403 | Forbidden - User lacks permission to update this record |
| 404 | Not Found - User extra record with specified ID does not exist |

---

<a id="patch-user_extra-id"></a>

### PATCH /user_extra/{id}/

**Description:** Partially updates an existing user extra information record. Unlike PUT, PATCH allows you to update only specific fields without affecting other stored data. Fields not included in the request remain unchanged. This is the recommended method for most update operations as it provides granular control and prevents accidental data loss.

**Use Cases:**
- Update a user's telephone number or address without changing other information
- Add or modify custom fields while preserving existing data
- Update specific demographic information based on user input
- Implement incremental profile completion workflows

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_extra/125/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| id | integer | path | Yes | The unique identifier of the user extra record to update |
| data | object | body | Yes | JSON object containing only the fields to update |

**Request Body Schema:**
Same fields as POST endpoint, but all are optional - include only the fields you want to update.

**cURL Example:**
```bash
curl -X PATCH "https://gate.zequenze.com/api/v1/user_extra/125/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "telephone": "+1-555-1234",
    "address": "789 Pine Street, Suite 200",
    "custom_field_1": "Diamond Tier"
  }'
```

**Example Response:**
```json
{
  "id": 125,
  "parent": 42,
  "title": "Dr.",
  "gender": "f",
  "birthday": "1992-08-14",
  "age": 31,
  "age_range": "30-34",
  "telephone": "+1-555-1234",
  "address": "789 Pine Street, Suite 200",
  "city": "Portland",
  "state": "OR",
  "postal_code": "97201",
  "country": "United States",
  "country_id": "US",
  "company": "Creative Agency Co",
  "tax_id": "555-66-7777",
  "passport_number": null,
  "hometown": "Eugene",
  "location": "Portland, OR",
  "locale": "en_US",
  "event": "Design Summit 2024",
  "accept_terms": true,
  "custom_field_1": "Diamond Tier",
  "custom_field_2": "Newsletter: Yes",
  "custom_field_3": "Preferred contact: Phone",
  "custom_field_4": "Emergency contact: Jane Doe",
  "custom_field_5": null,
  "custom_field_6": null,
  "custom_field_7": null,
  "custom_field_8": null
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - User extra record successfully updated |
| 400 | Bad Request - Invalid data provided for the fields being updated |
| 401 | Unauthorized - Invalid or missing authentication token |
| 403 | Forbidden - User lacks permission to update this record |
| 404 | Not Found - User extra record with specified ID does not exist |

---

<a id="delete-user_extra-id"></a>

### DELETE /user_extra/{id}/

**Description:** Permanently deletes a user extra information record. This operation cannot be undone. Use this endpoint when a user requests data deletion, when cleaning up test data, or when a user account is being fully removed from the system. Note that this only deletes the extra information record, not the parent user account.

**Use Cases:**
- Comply with data deletion requests (GDPR, privacy regulations)
- Remove user profile data when deactivating or deleting user accounts
- Clean up test or duplicate records
- Reset user profiles by deleting and recreating extra information

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_extra/125/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| id | integer | path | Yes | The unique identifier of the user extra record to delete |

**cURL Example:**
```bash
curl -X DELETE "https://gate.zequenze.com/api/v1/user_extra/125/" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

**Example Response:**
```
No content returned (204 status code indicates successful deletion)
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 204 | No Content - User extra record successfully deleted |
| 401 | Unauthorized - Invalid or missing authentication token |
| 403 | Forbidden - User lacks permission to delete this record |
| 404 | Not Found - User extra record with specified ID does not exist or already deleted |

---

## Common Use Cases

### Use Case 1: Complete User Onboarding with Extended Profile

When onboarding a new user to your application, you first create the core user account through the user authentication endpoints in GATE, then immediately create an associated user extra record to capture additional profile information.

**Workflow:**
1. Create user account via authentication API (receives user ID)
2. POST to `/user_extra/` with the new user ID as parent
3. Collect and store demographic, contact, and custom business fields

This approach allows you to maintain a clean separation between authentication data and extended profile information while providing a seamless registration experience.

---

### Use Case 2: Progressive Profile Completion

Implement a progressive profile completion system where users can gradually add information to their profiles over time. Start with minimal required fields and use PATCH operations to incrementally add details.

**Workflow:**
1. Initial registration: POST with only `parent` and `accept_terms`
2. First login: PATCH to add basic contact info (`telephone`, `city`, `country`)
3. Profile enhancement: PATCH to add demographic data and preferences
4. Event registration: PATCH to update `event` and event-specific custom fields

This pattern improves user experience by avoiding long registration forms while still collecting comprehensive data over time.

---

### Use Case 3: Organization-Wide User Data Export

Generate reports or exports of user information across an entire organization for analytics, compliance, or migration purposes.

**Workflow:**
1. GET `/user_extra/?parent__organization_id=123&limit=100` to retrieve first batch
2. Process returned records and extract `next` URL from pagination
3. Continue following `next` URLs until all records are retrieved
4. Aggregate data for reporting, CSV export, or data warehouse loading

Use pagination to handle large datasets efficiently and avoid timeout or memory issues.

---

### Use Case 4: Event Attendee Management

Collect and manage detailed attendee information for conferences, webinars, or events by leveraging the `event` field and custom fields for event-specific data.

**Workflow:**
1. During event registration: POST user extra records with `event` field populated
2. Store event-specific data in custom fields (e.g., dietary restrictions, session preferences)
3. Query attendees: GET `/user_extra/?parent__organization_id=123` filtered by event
4. Update attendee status: PATCH to modify custom fields as needed (check-in status, badge printed, etc.)

This provides a flexible system for managing varying event requirements without schema changes.

---

### Use Case 5: Multi-Locale User Management

Support international users with different locale preferences and location-specific information by properly utilizing the locale, country, and location fields.

**Workflow:**
1. Detect user's locale during registration (browser settings, IP geolocation)
2. POST user extra record with `locale`, `country`, and `country_id` fields
3. Use locale information to customize communication preferences
4. PATCH to update location information when users move or travel

This enables personalized experiences based on user location and language preferences while maintaining accurate demographic data.

---

## Best Practices

**Data Validation:**
- Always validate date formats (YYYY-MM-DD) before submitting birthday fields
- Ensure gender values are limited to "m", "f", or "o" to avoid validation errors
- Validate parent user IDs exist before creating user extra records
- Use appropriate field types (e.g., integers for age, strings for custom fields)

**Efficient Querying:**
- Use pagination (`limit` and `offset`) when retrieving large datasets to avoid performance issues
- Filter by `parent__organization_id` when working with organization-specific data
- Cache frequently accessed user extra records to reduce API calls
- Consider implementing local storage for user profile data that changes infrequently

**Update Operations:**
- Prefer PATCH over PUT for most update scenarios to prevent accidental data loss
- Only use PUT when you need to completely reset/replace a user's extra information
- Validate required fields before submission to avoid partial update failures
- Implement optimistic locking or version checking for concurrent update scenarios

**Privacy and Security:**
- Store only necessary personal information and comply with data privacy regulations (GDPR, CCPA)
- Implement proper access controls to ensure users can only access their own data or authorized records
- Use HTTPS for all API communications to protect sensitive user information in transit
- Regularly audit and purge unnecessary personal data using the DELETE endpoint
- Consider encrypting sensitive fields (passport numbers, tax IDs) at the application layer

**Custom Fields Management:**
- Document the purpose and format of each custom field used in your organization
- Maintain consistency in custom field usage across your application
- Consider implementing a naming convention for custom fields (e.g., custom_field_1 always contains membership tier)
- Use JSON schema validation in your application to ensure custom field data consistency

**Error Handling:**
- Implement retry logic with exponential backoff for transient network errors
- Log API errors with sufficient context for debugging (user ID, request parameters)
- Provide user-friendly error messages while logging detailed technical errors
- Handle 404 errors gracefully when querying potentially deleted records

**Performance Optimization:**
- Batch user extra record creation when onboarding multiple users simultaneously
- Use the `device_info` parameter only when device data is actually needed
- Implement caching strategies for frequently accessed user profile data
- Consider implementing webhooks or change notifications to invalidate caches when data changes

# User Token

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/user_token/`](#get-user_token) | <a href="https://gate.zequenze.com/api#/user_token/user_token_list" target="_blank">Swagger ↗</a> |
| `POST` | [`/user_token/`](#post-user_token) | <a href="https://gate.zequenze.com/api#/user_token/user_token_create" target="_blank">Swagger ↗</a> |
| `GET` | [`/user_token/{id}/`](#get-user_token-id) | <a href="https://gate.zequenze.com/api#/user_token/user_token_read" target="_blank">Swagger ↗</a> |
| `PUT` | [`/user_token/{id}/`](#put-user_token-id) | <a href="https://gate.zequenze.com/api#/user_token/user_token_update" target="_blank">Swagger ↗</a> |
| `PATCH` | [`/user_token/{id}/`](#patch-user_token-id) | <a href="https://gate.zequenze.com/api#/user_token/user_token_partial_update" target="_blank">Swagger ↗</a> |
| `DELETE` | [`/user_token/{id}/`](#delete-user_token-id) | <a href="https://gate.zequenze.com/api#/user_token/user_token_delete" target="_blank">Swagger ↗</a> |

---
> The User Token API manages users within the GATE system, including their authentication credentials, AAA (Authentication, Authorization, and Accounting) profiles, and time-based access controls. These endpoints allow you to create, retrieve, update, and delete user accounts with detailed profile information and token-based time management for access control systems.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The User Token API provides comprehensive user management functionality for the GATE system. This API category is designed for managing user accounts that require time-based access control, typically used in scenarios where users need allocated time credits for services or resources.

**Key Features:**
- **User Account Management**: Create, read, update, and delete user accounts with detailed profile information
- **AAA Profile Integration**: Associate users with Authentication, Authorization, and Accounting profiles
- **Time-Based Access Control**: Manage user time allocations (in seconds) for token-based systems
- **Organization Filtering**: Group and filter users by organization
- **Balance Tracking**: Monitor remaining time balances for users
- **External System Integration**: Link users to external systems via external_id references

**Common Use Cases:**
- Internet café or hotspot user management
- Time-based service access control
- Guest network authentication systems
- Subscription-based time allocation services
- Multi-tenant user management with organizational boundaries

The API uses standard REST principles with JSON responses and supports pagination for list operations. User time is tracked in seconds, making it suitable for precise time-based billing and access control scenarios.

---

## Endpoints

<a id="get-user_token"></a>

### GET /user_token/

**Description:** Retrieves a paginated list of all users in the system, including their AAA profile information. This endpoint supports filtering by username and organization, and can optionally include remaining time balance information.

**Use Cases:**
- Display all users in an administrative dashboard
- Filter users by specific organizations for multi-tenant systems
- Search for specific users by username
- Monitor user balances across the system

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_token/?username=john_doe&organization=acme_corp&balance=true&limit=20&offset=0
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| username | string | query | No | Filter users by exact username match |
| organization | string | query | No | Filter users by organization identifier |
| limit | integer | query | No | Number of results per page (default: 20) |
| offset | integer | query | No | Starting index for pagination (default: 0) |
| balance | boolean | query | No | Include remaining time balance in seconds |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/user_token/?balance=true&limit=10" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 150,
  "next": "https://gate.zequenze.com/api/v1/user_token/?limit=10&offset=10",
  "previous": null,
  "results": [
    {
      "id": 1,
      "username": "john_doe",
      "external_id": "EXT-USER-001",
      "klass": "premium",
      "is_active": true,
      "organization": 1,
      "description": "Premium user account",
      "date_joined": "2024-01-15T10:30:00Z",
      "last_login": "2024-01-20T14:25:00Z",
      "expiration": "2024-12-31T23:59:59Z",
      "profile": ["internet_access", "wifi_premium"],
      "user_time": 3600
    },
    {
      "id": 2,
      "username": "jane_smith",
      "external_id": "EXT-USER-002",
      "klass": "standard",
      "is_active": true,
      "organization": 1,
      "description": "Standard user account",
      "date_joined": "2024-01-16T09:15:00Z",
      "last_login": "2024-01-19T16:45:00Z",
      "expiration": null,
      "profile": ["internet_access"],
      "user_time": 1800
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated user list |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions |

---

<a id="post-user_token"></a>

### POST /user_token/

**Description:** Creates a new user account with AAA profile information. This endpoint allows you to set up complete user profiles including authentication credentials, organizational assignment, and initial time allocations.

**Use Cases:**
- Register new users in the system
- Bulk user creation for organizations
- Set up guest accounts with specific time limits
- Create users with predefined AAA profiles

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_token/
```

**Request Body Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| username | string | Yes | Unique username (150 chars max, letters/digits/@/./+/-/:/ |/_ only) |
| password | string | No | User password for authentication |
| email | string | No | User email address |
| first_name | string | No | User's first name |
| last_name | string | No | User's last name |
| external_id | string | No | Reference ID for external systems |
| klass | string | No | Service class reference (e.g., "premium", "standard") |
| is_active | boolean | No | Whether user account is active (default: true) |
| organization | integer | No | Organization ID to associate user with |
| description | string | No | Descriptive text about the user |
| expiration | string | No | ISO 8601 date-time when user expires |
| avatar_url | string | No | URL to user's avatar image |
| profile | array | No | Array of AAA profile short-names |

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/user_token/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "new_user",
    "password": "secure_password123",
    "email": "newuser@example.com",
    "first_name": "New",
    "last_name": "User",
    "external_id": "EXT-USER-003",
    "klass": "premium",
    "is_active": true,
    "organization": 1,
    "description": "Newly created premium user",
    "expiration": "2024-12-31T23:59:59Z",
    "profile": ["internet_access", "wifi_premium", "email_access"]
  }'
```

**Example Response:**
```json
{
  "id": 3,
  "username": "new_user",
  "external_id": "EXT-USER-003",
  "klass": "premium",
  "email": "newuser@example.com",
  "first_name": "New",
  "last_name": "User",
  "is_active": true,
  "organization": 1,
  "description": "Newly created premium user",
  "date_joined": "2024-01-21T11:30:00Z",
  "first_login": null,
  "last_login": null,
  "expiration": "2024-12-31T23:59:59Z",
  "avatar_url": null,
  "profile": ["internet_access", "wifi_premium", "email_access"]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - User successfully created |
| 400 | Bad Request - Invalid data or duplicate username |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions |

---

<a id="get-user_token-id"></a>

### GET /user_token/{id}/

**Description:** Retrieves detailed information for a specific user by their ID, including AAA profile information and optionally their remaining time balance.

**Use Cases:**
- Display user profile in administrative interface
- Check user details before granting access
- Retrieve user information for authentication systems
- Monitor individual user time balances

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_token/123/?balance=true
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| id | integer | path | Yes | Unique identifier of the user |
| balance | boolean | query | No | Include remaining time balance in seconds |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/user_token/1/?balance=true" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "id": 1,
  "username": "john_doe",
  "external_id": "EXT-USER-001",
  "klass": "premium",
  "is_active": true,
  "organization": 1,
  "description": "Premium user account",
  "date_joined": "2024-01-15T10:30:00Z",
  "last_login": "2024-01-20T14:25:00Z",
  "expiration": "2024-12-31T23:59:59Z",
  "profile": ["internet_access", "wifi_premium", "email_access"],
  "user_time": 3600
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns user details |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions |
| 404 | Not Found - User with specified ID does not exist |

---

<a id="put-user_token-id"></a>

### PUT /user_token/{id}/

**Description:** Completely updates an existing user account, replacing all modifiable fields. This is a full update operation that requires all fields you want to preserve to be included in the request.

**Use Cases:**
- Complete user profile updates
- Bulk user information changes
- Resetting user configurations
- Migrating user data between systems

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_token/123/
```

**cURL Example:**
```bash
curl -X PUT "https://gate.zequenze.com/api/v1/user_token/1/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john_doe_updated",
    "external_id": "EXT-USER-001-UPDATED",
    "klass": "enterprise",
    "is_active": true,
    "organization": 2,
    "description": "Updated to enterprise user",
    "expiration": "2025-12-31T23:59:59Z",
    "profile": ["internet_access", "wifi_premium", "email_access", "vpn_access"],
    "user_time": 7200
  }'
```

**Example Response:**
```json
{
  "id": 1,
  "username": "john_doe_updated",
  "external_id": "EXT-USER-001-UPDATED",
  "klass": "enterprise",
  "is_active": true,
  "organization": 2,
  "description": "Updated to enterprise user",
  "date_joined": "2024-01-15T10:30:00Z",
  "last_login": "2024-01-20T14:25:00Z",
  "expiration": "2025-12-31T23:59:59Z",
  "profile": ["internet_access", "wifi_premium", "email_access", "vpn_access"],
  "user_time": 7200
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - User updated successfully |
| 400 | Bad Request - Invalid data provided |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions |
| 404 | Not Found - User with specified ID does not exist |

---

<a id="patch-user_token-id"></a>

### PATCH /user_token/{id}/

**Description:** Partially updates a user account, allowing you to modify only specific fields without affecting other user data. This is ideal for making incremental changes to user accounts.

**Use Cases:**
- Update user time balance without changing other details
- Modify user status (active/inactive)
- Add or remove specific AAA profiles
- Update expiration dates or organizational assignments

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_token/123/
```

**cURL Example:**
```bash
curl -X PATCH "https://gate.zequenze.com/api/v1/user_token/1/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_time": 5400,
    "description": "Time balance updated",
    "profile": ["internet_access", "wifi_premium"]
  }'
```

**Example Response:**
```json
{
  "id": 1,
  "username": "john_doe",
  "external_id": "EXT-USER-001",
  "klass": "premium",
  "is_active": true,
  "organization": 1,
  "description": "Time balance updated",
  "date_joined": "2024-01-15T10:30:00Z",
  "last_login": "2024-01-20T14:25:00Z",
  "expiration": "2024-12-31T23:59:59Z",
  "profile": ["internet_access", "wifi_premium"],
  "user_time": 5400
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - User updated successfully |
| 400 | Bad Request - Invalid data provided |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions |
| 404 | Not Found - User with specified ID does not exist |

---

<a id="delete-user_token-id"></a>

### DELETE /user_token/{id}/

**Description:** Permanently removes a user account from the system. This action cannot be undone and will delete all associated user data and tokens.

**Use Cases:**
- Remove expired or unused accounts
- Clean up test or temporary users
- Comply with data retention policies
- Decommission user accounts

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/user_token/123/
```

**cURL Example:**
```bash
curl -X DELETE "https://gate.zequenze.com/api/v1/user_token/1/" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 204 | No Content - User successfully deleted |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions |
| 404 | Not Found - User with specified ID does not exist |

---

## Common Use Cases

### Use Case 1: Internet Café User Management
Create time-based user accounts for internet café customers with specific time allocations. Use POST to create users with `user_time` values, then use PATCH to update remaining time as customers use the service.

### Use Case 2: Guest Network Access
Set up temporary guest accounts with expiration dates and limited AAA profiles. Use the `expiration` field to automatically invalidate accounts and the `profile` array to restrict access to specific services.

### Use Case 3: Multi-Tenant Organization Management
Filter and manage users across different organizations using the `organization` parameter. Use GET with organization filtering to display users per tenant, and ensure proper isolation between organizations.

### Use Case 4: Subscription Service Time Tracking
Monitor user time balances across your subscriber base using the `balance=true` parameter with GET requests. Use PATCH operations to add time when users purchase additional credits.

### Use Case 5: External System Integration
Synchronize users with external databases or CRM systems using the `external_id` field to maintain references between systems while managing authentication through GATE.

---

## Best Practices

- **Time Management**: Always specify time values in seconds for consistency. Consider implementing automatic time deduction mechanisms that integrate with these API endpoints.

- **Pagination**: When retrieving large user lists, use appropriate `limit` and `offset` values to prevent timeouts and improve performance. Start with limit=50 and adjust based on your needs.

- **Balance Monitoring**: Use the `balance=true` parameter judiciously as it adds computational overhead. Only include it when you specifically need current balance information.

- **Security Considerations**: Never store passwords in plain text. The API handles password hashing automatically, but ensure your client applications don't log or expose password data.

- **Error Handling**: Implement retry logic for network failures and handle 404 errors gracefully when users might have been deleted by other processes.

- **Bulk Operations**: For creating or updating multiple users, implement batching with appropriate delays to avoid overwhelming the API server.

- **Profile Management**: Maintain a reference list of available AAA profiles in your application to ensure you're assigning valid profiles to users.

---

# Aaa Accounting

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/aaa_accounting/`](#get-aaa_accounting) | <a href="https://gate.zequenze.com/api#/aaa_accounting/aaa_accounting_list" target="_blank">Swagger ↗</a> |
| `GET` | [`/aaa_accounting/{radacctid}/`](#get-aaa_accounting-radacctid) | <a href="https://gate.zequenze.com/api#/aaa_accounting/aaa_accounting_read" target="_blank">Swagger ↗</a> |

---
> The AAA Accounting endpoints provide access to RADIUS accounting records that track user authentication, authorization, and accounting (AAA) sessions. These endpoints allow you to retrieve detailed session information including connection times, data usage, network details, and session status for monitoring and reporting purposes.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The AAA Accounting API category provides comprehensive access to RADIUS accounting data that tracks network access sessions across your organization. These endpoints are essential for network administrators, security teams, and compliance officers who need to monitor user activity, track bandwidth usage, and generate detailed reports on network access patterns.

**Key Features:**
- **Session Tracking**: Monitor active and historical user sessions with detailed start/stop times
- **Data Usage Monitoring**: Track input/output data volumes for bandwidth analysis and billing
- **Network Diagnostics**: Access detailed connection information including NAS details, IP addresses, and connection methods
- **Multi-dimensional Filtering**: Filter records by user, location, access point, client, and time ranges for targeted analysis
- **Real-time Status**: Distinguish between active and completed sessions for live monitoring

**Common Use Cases:**
- Generate compliance reports showing user access patterns and session durations
- Monitor bandwidth usage across different locations and access points
- Troubleshoot network connectivity issues by examining session termination causes
- Track user behavior for security analysis and anomaly detection
- Create billing reports based on session time and data usage

The accounting records follow the RADIUS accounting standard, capturing comprehensive session metadata from network access servers (NAS) across your infrastructure.

---

## Endpoints

<a id="get-aaa_accounting"></a>

### GET /aaa_accounting/

**Description:** Retrieves a paginated list of AAA accounting records with comprehensive filtering options. This endpoint is the primary method for accessing historical and active session data, allowing you to filter by time ranges, users, locations, and session status for detailed network usage analysis.

**Use Cases:**
- Generate monthly bandwidth usage reports for specific locations or users
- Monitor active sessions to identify current network load and user activity
- Audit user access patterns for compliance and security purposes
- Troubleshoot connectivity issues by examining recent session terminations

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_accounting/?start_date=2024-01-01&end_date=2024-01-31&session_status=active&limit=50
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| start_date | string | query | No | Filter records from this date/time in ISO format (2024-01-01, 2024-01-01 00:01:00, 2024-01-01 00:01:00+00:00) |
| end_date | string | query | No | Filter records until this date/time in ISO format (2024-01-31, 2024-01-31 23:59:59, 2024-01-31 23:59:59+00:00) |
| user | integer | query | No | Filter transactions by specific user ID |
| access_point | integer | query | No | Filter transactions by specific access point ID |
| location | integer | query | No | Filter transactions by specific location ID |
| client | integer | query | No | Filter transactions by specific client ID |
| cursor | string | query | No | Pagination cursor value for cursor-based pagination |
| limit | integer | query | No | Number of results per page (default: 20, max: 100) |
| session_status | string | query | No | Filter by session status: 'all', 'active', or 'inactive' |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/aaa_accounting/?start_date=2024-01-01&session_status=active&limit=25" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "next": "https://gate.zequenze.com/api/v1/aaa_accounting/?cursor=eyJpZCI6MTAwfQ%3D%3D&limit=25",
  "previous": null,
  "results": [
    {
      "radacctid": 12345,
      "acctsessionid": "8C:DC:D4:B2:FE:E8-01-5E-7B-9A-2C",
      "acctuniqueid": "f47ac10b58cc4372a5670e02b2c3d479",
      "username": "john.doe@company.com",
      "groupname": "employees",
      "realm": "company.com",
      "nasipaddress": "192.168.1.10",
      "nasportid": "wireless-controller-1",
      "nasporttype": "Wireless-IEEE-802.11",
      "acctstarttime": "2024-01-15T09:30:15Z",
      "acctupdatetime": "2024-01-15T11:45:30Z",
      "acctstoptime": null,
      "acctinterval": 300,
      "acctsessiontime": 8115,
      "acctauthentic": "RADIUS",
      "connectinfo_start": "CONNECT 802.11g 54Mbps",
      "connectinfo_stop": null,
      "acctinputoctets": 45678912,
      "acctoutputoctets": 123456789,
      "calledstationid": "AP-Office-01",
      "callingstationid": "8C:DC:D4:B2:FE:E8",
      "acctterminatecause": null,
      "servicetype": "Framed-User",
      "framedprotocol": "PPP",
      "framedipaddress": "10.0.1.155",
      "organization_id": "org_001",
      "user_id": "user_12345",
      "user_transaction_id": "txn_abc123",
      "client_id": "client_001",
      "client_short_name": "Main Office",
      "location_id": "loc_001",
      "access_point_id": "ap_001",
      "access_point_name": "Office-WiFi-01",
      "location_name": "Corporate Headquarters",
      "nasidentifier": "wireless-nas-01",
      "klass": "premium",
      "access_point_mac_addr": "00:1B:44:11:3A:B7",
      "ssid": "Corporate-WiFi"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns the paginated list of accounting records |
| 400 | Bad Request - Invalid date format or parameter values |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions to access accounting data |

---

<a id="get-aaa_accounting-radacctid"></a>

### GET /aaa_accounting/{radacctid}/

**Description:** Retrieves detailed information for a specific AAA accounting record by its unique RADIUS accounting ID. This endpoint provides complete session details including all RADIUS attributes, connection metadata, and organizational context for in-depth session analysis.

**Use Cases:**
- Investigate specific user sessions for security or compliance audits
- Troubleshoot individual connection issues with detailed session metadata
- Extract complete session information for billing or usage reporting
- Analyze session termination causes and connection quality metrics

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_accounting/12345/
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| radacctid | integer | path | Yes | Unique RADIUS accounting record identifier |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/aaa_accounting/12345/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "radacctid": 12345,
  "acctsessionid": "8C:DC:D4:B2:FE:E8-01-5E-7B-9A-2C",
  "acctuniqueid": "f47ac10b58cc4372a5670e02b2c3d479",
  "username": "jane.smith@company.com",
  "groupname": "administrators",
  "realm": "company.com",
  "nasipaddress": "192.168.1.15",
  "nasportid": "ethernet-switch-port-24",
  "nasporttype": "Ethernet",
  "acctstarttime": "2024-01-15T08:00:00Z",
  "acctupdatetime": "2024-01-15T17:30:45Z",
  "acctstoptime": "2024-01-15T17:30:45Z",
  "acctinterval": 600,
  "acctsessiontime": 34245,
  "acctauthentic": "Local",
  "connectinfo_start": "CONNECT Ethernet 1000Mbps Full-Duplex",
  "connectinfo_stop": "DISCONNECT User-Request",
  "acctinputoctets": 987654321,
  "acctoutputoctets": 456789123,
  "calledstationid": "SW-Floor2-Port24",
  "callingstationid": "00:1A:2B:3C:4D:5E",
  "acctterminatecause": "User-Request",
  "servicetype": "Administrative-User",
  "framedprotocol": "PPP",
  "framedipaddress": "10.0.2.50",
  "organization_id": "org_001",
  "user_id": "user_67890",
  "user_transaction_id": "txn_xyz789",
  "client_id": "client_002",
  "client_short_name": "IT Department",
  "location_id": "loc_002",
  "access_point_id": "sw_001",
  "access_point_name": "Floor2-Switch-01",
  "location_name": "Second Floor Office",
  "nasidentifier": "ethernet-nas-02",
  "klass": "administrative",
  "access_point_mac_addr": "00:50:56:A1:B2:C3",
  "ssid": null
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns the detailed accounting record |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions to access this record |
| 404 | Not Found - Accounting record with specified ID does not exist |

---

## Common Use Cases

### Use Case 1: Monthly Bandwidth Usage Report
Generate comprehensive usage reports by filtering records within specific date ranges and aggregating data usage by location or user groups. Use the list endpoint with `start_date`, `end_date`, and `location` parameters to create detailed bandwidth consumption reports.

### Use Case 2: Real-time Session Monitoring
Monitor currently active network sessions by filtering with `session_status=active` to identify peak usage times, current user load, and active connection patterns across different access points and locations.

### Use Case 3: Security Incident Investigation
Investigate suspicious network activity by retrieving specific user sessions during incident timeframes, examining session termination causes, connection sources, and data transfer patterns for forensic analysis.

### Use Case 4: Compliance Auditing
Create detailed audit trails by filtering sessions for specific users or time periods, documenting access patterns, session durations, and data usage for regulatory compliance requirements.

### Use Case 5: Network Performance Analysis
Analyze connection quality and performance by examining session termination causes, connection types, and data transfer rates across different access points to identify infrastructure optimization opportunities.

---

## Best Practices

- **Use Date Filtering**: Always apply appropriate `start_date` and `end_date` filters to limit result sets and improve query performance, especially when dealing with large datasets spanning multiple months.

- **Implement Pagination**: Use the `limit` parameter (recommended: 50-100 records per request) and cursor-based pagination for efficient data retrieval when processing large volumes of accounting records.

- **Filter Strategically**: Combine multiple filter parameters (user, location, access_point) to narrow down results and reduce API response times while minimizing unnecessary data transfer.

- **Cache Session Data**: For frequently accessed reports or dashboards, implement appropriate caching strategies as accounting data is typically historical and doesn't change once sessions are completed.

- **Monitor Active Sessions**: Use `session_status=active` filtering sparingly and implement reasonable polling intervals (5-10 minutes) to avoid overwhelming the API when monitoring real-time sessions.

- **Handle Time Zones**: Ensure consistent timezone handling when filtering by dates, preferably using UTC timestamps with explicit timezone offsets in ISO format.

- **Error Handling**: Implement robust error handling for common scenarios like missing records (404), rate limiting (429), and temporary service unavailability (503).

- **Security Considerations**: AAA accounting data contains sensitive user information - ensure API tokens are securely stored and access is limited to authorized personnel only.

---

# Aaa Profile

## Endpoints Summary

| Method | Path | Swagger |
|:------:|------|:-------:|
| `GET` | [`/aaa_profile/`](#get-aaa_profile) | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_list" target="_blank">Swagger ↗</a> |
| `POST` | [`/aaa_profile/`](#post-aaa_profile) | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_create" target="_blank">Swagger ↗</a> |
| `GET` | [`/aaa_profile/{id}/`](#get-aaa_profile-id) | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_read" target="_blank">Swagger ↗</a> |
| `PUT` | [`/aaa_profile/{id}/`](#put-aaa_profile-id) | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_update" target="_blank">Swagger ↗</a> |
| `PATCH` | [`/aaa_profile/{id}/`](#patch-aaa_profile-id) | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_partial_update" target="_blank">Swagger ↗</a> |
| `DELETE` | [`/aaa_profile/{id}/`](#delete-aaa_profile-id) | <a href="https://gate.zequenze.com/api#/aaa_profile/aaa_profile_delete" target="_blank">Swagger ↗</a> |

---
> The AAA Profile API enables management of Authentication, Authorization, and Accounting profiles used for network access control. These endpoints allow you to create, configure, and manage RADIUS attribute profiles that define user authentication parameters and access policies. Common use cases include setting up user access levels, configuring network device authentication, and managing RADIUS reply and check attributes for network security.

**Base URL:** `https://gate.zequenze.com/api/v1`

**Authentication:** All endpoints require a Bearer token:
```
Authorization: Bearer <your-api-token>
```

---

## Overview

The AAA Profile API provides comprehensive management of Authentication, Authorization, and Accounting profiles within the GATE platform. AAA profiles define sets of RADIUS attributes that control network access authentication and authorization policies.

**Key Concepts:**
- **AAA Profiles**: Named collections of RADIUS attributes that define authentication and authorization rules
- **Reply Attributes**: RADIUS attributes sent back to the authenticating device after successful authentication
- **Check Attributes**: RADIUS attributes used to validate authentication requests before granting access
- **Attribute Operators**: Define how attributes are processed (assignment, comparison, addition, etc.)

**Common Scenarios:**
- Setting up different access levels for various user groups (admin, user, guest)
- Configuring VLAN assignments based on user authentication
- Managing bandwidth limitations and session timeouts
- Implementing role-based access control for network resources
- Creating standardized authentication profiles for network devices

The API follows REST principles with full CRUD operations, supporting both complete updates (PUT) and partial modifications (PATCH) for flexible profile management.

---

## Endpoints

<a id="get-aaa_profile"></a>

### GET /aaa_profile/

**Description:** Retrieves a paginated list of all AAA profiles in your organization. This endpoint is essential for viewing existing authentication profiles, discovering available configurations, and implementing profile selection interfaces.

**Use Cases:**
- Displaying available authentication profiles in management dashboards
- Implementing profile selection dropdowns in user interfaces
- Auditing existing authentication configurations
- Synchronizing profiles with external systems

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/?limit=25&offset=0
```

**Parameters:**

| Parameter | Type | In | Required | Description |
|-----------|------|-----|----------|-------------|
| limit | integer | query | No | Number of results to return per page (default: 20, max: 100) |
| offset | integer | query | No | The initial index from which to return results for pagination |

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/aaa_profile/?limit=10&offset=0" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "count": 15,
  "next": "https://gate.zequenze.com/api/v1/aaa_profile/?limit=10&offset=10",
  "previous": null,
  "results": [
    {
      "id": 1,
      "name": "Admin Access Profile",
      "short_name": "admin-access",
      "description": "Full administrative access with elevated privileges",
      "organization_id": "org_12345",
      "reply_attribute": [
        {
          "attribute": "Framed-IP-Address",
          "op": "=",
          "value": "192.168.1.100"
        }
      ],
      "check_attribute": [
        {
          "attribute": "User-Name",
          "op": "!=",
          "value": "guest"
        }
      ]
    },
    {
      "id": 2,
      "name": "Guest Network Profile",
      "short_name": "guest-network",
      "description": "Limited access profile for guest users",
      "organization_id": "org_12345",
      "reply_attribute": [
        {
          "attribute": "Tunnel-Type",
          "op": ":=",
          "value": "VLAN"
        }
      ],
      "check_attribute": []
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns paginated list of AAA profiles |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions |
| 500 | Internal Server Error - Server processing error |

---

<a id="post-aaa_profile"></a>

### POST /aaa_profile/

**Description:** Creates a new AAA profile with specified RADIUS attributes and configuration settings. This endpoint enables you to programmatically define new authentication and authorization policies for your network infrastructure.

**Use Cases:**
- Automating AAA profile creation during network onboarding
- Creating standardized profiles for different user roles
- Implementing dynamic profile generation based on organizational requirements
- Bulk creation of profiles for multi-tenant environments

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/
```

**cURL Example:**
```bash
curl -X POST "https://gate.zequenze.com/api/v1/aaa_profile/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Developer Access Profile",
    "short_name": "dev-access",
    "description": "Development team access with limited administrative rights",
    "reply_attribute": [
      {
        "attribute": "Tunnel-Type",
        "op": ":=",
        "value": "VLAN"
      },
      {
        "attribute": "Tunnel-Medium-Type",
        "op": ":=",
        "value": "IEEE-802"
      }
    ],
    "check_attribute": [
      {
        "attribute": "NAS-Port-Type",
        "op": "==",
        "value": "Ethernet"
      }
    ]
  }'
```

**Request Body Example:**
```json
{
  "name": "Developer Access Profile",
  "short_name": "dev-access",
  "description": "Development team access with limited administrative rights",
  "reply_attribute": [
    {
      "attribute": "Tunnel-Type",
      "op": ":=",
      "value": "VLAN"
    },
    {
      "attribute": "Tunnel-Medium-Type",
      "op": ":=",
      "value": "IEEE-802"
    },
    {
      "attribute": "Session-Timeout",
      "op": "=",
      "value": "3600"
    }
  ],
  "check_attribute": [
    {
      "attribute": "NAS-Port-Type",
      "op": "==",
      "value": "Ethernet"
    },
    {
      "attribute": "Calling-Station-Id",
      "op": "=*",
      "value": "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"
    }
  ]
}
```

**Example Response:**
```json
{
  "id": 25,
  "name": "Developer Access Profile",
  "short_name": "dev-access",
  "description": "Development team access with limited administrative rights",
  "organization_id": "org_12345",
  "reply_attribute": [
    {
      "attribute": "Tunnel-Type",
      "op": ":=",
      "value": "VLAN"
    },
    {
      "attribute": "Tunnel-Medium-Type",
      "op": ":=",
      "value": "IEEE-802"
    },
    {
      "attribute": "Session-Timeout",
      "op": "=",
      "value": "3600"
    }
  ],
  "check_attribute": [
    {
      "attribute": "NAS-Port-Type",
      "op": "==",
      "value": "Ethernet"
    },
    {
      "attribute": "Calling-Station-Id",
      "op": "=*",
      "value": "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 201 | Created - AAA profile successfully created |
| 400 | Bad Request - Invalid data format or missing required fields |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions |
| 409 | Conflict - Profile with same short_name already exists |

---

<a id="get-aaa_profile-id"></a>

### GET /aaa_profile/{id}/

**Description:** Retrieves detailed information about a specific AAA profile by its unique identifier. This endpoint provides complete profile configuration including all RADIUS attributes, operators, and values.

**Use Cases:**
- Viewing complete profile configuration for auditing purposes
- Retrieving profile details for editing or cloning operations
- Validating profile settings before applying to network devices
- Debugging authentication issues by examining profile attributes

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/15/
```

**cURL Example:**
```bash
curl -X GET "https://gate.zequenze.com/api/v1/aaa_profile/15/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json"
```

**Example Response:**
```json
{
  "id": 15,
  "name": "Network Administrator Profile",
  "short_name": "network-admin",
  "description": "Full network administrative access with monitoring capabilities",
  "organization_id": "org_12345",
  "reply_attribute": [
    {
      "attribute": "Service-Type",
      "op": "=",
      "value": "Administrative-User"
    },
    {
      "attribute": "Framed-Protocol",
      "op": ":=",
      "value": "PPP"
    },
    {
      "attribute": "Idle-Timeout",
      "op": "=",
      "value": "1800"
    }
  ],
  "check_attribute": [
    {
      "attribute": "User-Password",
      "op": "!=",
      "value": ""
    },
    {
      "attribute": "NAS-IP-Address",
      "op": "==",
      "value": "192.168.100.1"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Returns the requested AAA profile |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions to view this profile |
| 404 | Not Found - AAA profile with specified ID does not exist |

---

<a id="put-aaa_profile-id"></a>

### PUT /aaa_profile/{id}/

**Description:** Completely updates an existing AAA profile, replacing all current configuration with the provided data. This operation requires all required fields and overwrites the entire profile configuration.

**Use Cases:**
- Implementing major profile reconfiguration
- Standardizing profiles across multiple environments
- Applying template-based profile updates
- Migrating profile configurations between systems

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/15/
```

**cURL Example:**
```bash
curl -X PUT "https://gate.zequenze.com/api/v1/aaa_profile/15/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Updated Network Admin Profile",
    "short_name": "network-admin",
    "description": "Enhanced network administrative access with additional security",
    "reply_attribute": [
      {
        "attribute": "Service-Type",
        "op": "=",
        "value": "Administrative-User"
      },
      {
        "attribute": "Session-Timeout",
        "op": "=",
        "value": "7200"
      }
    ],
    "check_attribute": [
      {
        "attribute": "User-Password",
        "op": "!=",
        "value": ""
      },
      {
        "attribute": "Calling-Station-Id",
        "op": "=*",
        "value": "^00:11:22"
      }
    ]
  }'
```

**Request Body Example:**
```json
{
  "name": "Updated Network Admin Profile",
  "short_name": "network-admin",
  "description": "Enhanced network administrative access with additional security",
  "reply_attribute": [
    {
      "attribute": "Service-Type",
      "op": "=",
      "value": "Administrative-User"
    },
    {
      "attribute": "Session-Timeout",
      "op": "=",
      "value": "7200"
    },
    {
      "attribute": "Framed-MTU",
      "op": ":=",
      "value": "1500"
    }
  ],
  "check_attribute": [
    {
      "attribute": "User-Password",
      "op": "!=",
      "value": ""
    },
    {
      "attribute": "Calling-Station-Id",
      "op": "=*",
      "value": "^00:11:22"
    },
    {
      "attribute": "NAS-Port-Type",
      "op": "==",
      "value": "Ethernet"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Profile successfully updated |
| 400 | Bad Request - Invalid data format or missing required fields |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions to modify this profile |
| 404 | Not Found - AAA profile with specified ID does not exist |

---

<a id="patch-aaa_profile-id"></a>

### PATCH /aaa_profile/{id}/

**Description:** Partially updates an existing AAA profile, modifying only the specified fields while preserving other configuration elements. This is ideal for making targeted changes without affecting the entire profile.

**Use Cases:**
- Adding or removing specific RADIUS attributes
- Updating profile descriptions or names
- Modifying individual attribute values or operators
- Making incremental configuration changes

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/15/
```

**cURL Example:**
```bash
curl -X PATCH "https://gate.zequenze.com/api/v1/aaa_profile/15/" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "description": "Network administrator profile with enhanced security features",
    "reply_attribute": [
      {
        "attribute": "Service-Type",
        "op": "=",
        "value": "Administrative-User"
      },
      {
        "attribute": "Session-Timeout",
        "op": "=",
        "value": "14400"
      }
    ]
  }'
```

**Request Body Example:**
```json
{
  "description": "Network administrator profile with enhanced security features",
  "reply_attribute": [
    {
      "attribute": "Service-Type",
      "op": "=",
      "value": "Administrative-User"
    },
    {
      "attribute": "Session-Timeout",
      "op": "=",
      "value": "14400"
    },
    {
      "attribute": "Idle-Timeout",
      "op": "=",
      "value": "3600"
    }
  ]
}
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 200 | Success - Profile successfully updated |
| 400 | Bad Request - Invalid data format |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions to modify this profile |
| 404 | Not Found - AAA profile with specified ID does not exist |

---

<a id="delete-aaa_profile-id"></a>

### DELETE /aaa_profile/{id}/

**Description:** Permanently removes an AAA profile from the system. This operation cannot be undone and will affect any network devices or users currently assigned to this profile.

**Use Cases:**
- Cleaning up obsolete or unused authentication profiles
- Removing test profiles after development completion
- Implementing profile lifecycle management
- Decommissioning deprecated authentication methods

**Full URL Example:**
```bash
https://gate.zequenze.com/api/v1/aaa_profile/15/
```

**cURL Example:**
```bash
curl -X DELETE "https://gate.zequenze.com/api/v1/aaa_profile/15/" \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

**Response Codes:**

| Status | Description |
|--------|-------------|
| 204 | No Content - Profile successfully deleted |
| 401 | Unauthorized - Invalid or missing API token |
| 403 | Forbidden - Insufficient permissions to delete this profile |
| 404 | Not Found - AAA profile with specified ID does not exist |
| 409 | Conflict - Profile is in use and cannot be deleted |

---

## Common Use Cases

### Use Case 1: Setting Up Role-Based Network Access
Create different AAA profiles for various organizational roles (admin, employee, guest) with appropriate VLAN assignments and access restrictions. Use GET to list existing profiles, POST to create new role-specific profiles, and PATCH to adjust permissions as roles evolve.

### Use Case 2: Implementing Guest Network Authentication
Configure a guest access profile with time-limited sessions and restricted network access. Create a profile with Session-Timeout and Idle-Timeout reply attributes, then use Tunnel-Type attributes to direct guests to an isolated VLAN.

### Use Case 3: Managing Device-Specific Authentication
Set up profiles that validate specific device characteristics using check attributes like Calling-Station-Id (MAC address) and NAS-Port-Type to ensure only authorized devices can access network resources.

### Use Case 4: Bulk Profile Management for Multi-Site Networks
Use the list endpoint with pagination to audit existing profiles across multiple sites, then implement standardization by creating template profiles and updating existing ones using PUT operations.

### Use Case 5: Dynamic Profile Updates for Security Compliance
Monitor and update AAA profiles to maintain security compliance by modifying session timeouts, adding new check attributes for enhanced validation, and removing deprecated authentication methods using PATCH operations.

---

## Best Practices

- **Attribute Operators**: Understand the difference between reply attribute operators (=, +=, :=) and check attribute operators. Use := for assignment, == for exact comparison, and =* for regex pattern matching.

- **Profile Naming**: Use descriptive names and consistent short_name formats (slug format with hyphens) to ensure profiles are easily identifiable and manageable at scale.

- **Error Handling**: Always check response codes and implement proper error handling, especially for 409 conflicts when profile names already exist or when profiles are in use during deletion attempts.

- **Pagination Strategy**: When listing profiles, use appropriate limit values (recommended: 25-50 per page) and implement proper pagination handling for large profile sets.

- **Security Considerations**: Regularly audit check attributes to ensure authentication requirements remain secure, and avoid storing sensitive information in profile descriptions.

- **Profile Dependencies**: Before deleting profiles, ensure they're not actively assigned to users or network devices, as this could disrupt network access.

- **Testing Changes**: Use PATCH for incremental updates during testing, then apply complete configurations with PUT once changes are validated.

- **Version Control**: Maintain external documentation of profile configurations for rollback scenarios, as the API doesn't provide built-in versioning.