EU-Utility/docs/NEXUS_API_REFERENCE.md

790 lines
17 KiB
Markdown

# Entropia Nexus API Reference
> Complete technical documentation for the Entropia Nexus API
>
> **Version:** 1.0
> **Last Updated:** 2025-02-13
> **Base URL:** `https://api.entropianexus.com`
---
## Table of Contents
1. [Overview](#overview)
2. [Authentication](#authentication)
3. [Base Configuration](#base-configuration)
4. [Entity Types](#entity-types)
5. [Endpoints](#endpoints)
6. [Request Parameters](#request-parameters)
7. [Response Formats](#response-formats)
8. [Error Handling](#error-handling)
9. [Rate Limits](#rate-limits)
10. [Usage Examples](#usage-examples)
11. [Plugin API Integration](#plugin-api-integration)
12. [Field Name Conventions](#field-name-conventions)
---
## Overview
The Entropia Nexus API provides programmatic access to game data from Entropia Universe. It supports:
- **25+ entity types** (items, mobs, locations, skills, etc.)
- **Full-text search** with fuzzy matching
- **Market data** for trading analysis
- **Detailed entity information** with stats and properties
### Quick Start
```python
from core.nexus_api import get_nexus_api
# Get API instance
api = get_nexus_api()
# Search for items
results = api.search_items("ArMatrix")
# Get detailed info
details = api.get_item_details("armatrix_lp-35")
# Get market data
market = api.get_market_data("armatrix_lp-35")
```
---
## Authentication
The Entropia Nexus API is **public** and requires no authentication for read operations.
### Request Headers
Recommended headers for all requests:
```http
User-Agent: EU-Utility/1.0 (Entropia Universe Utility Tool)
Accept: application/json
Accept-Encoding: gzip
```
---
## Base Configuration
### API Client Settings
| Setting | Value | Description |
|---------|-------|-------------|
| `BASE_URL` | `https://api.entropianexus.com` | API endpoint |
| `API_VERSION` | `v1` | Current API version |
| `MAX_REQUESTS_PER_SECOND` | 5 | Rate limit for requests |
| `MIN_REQUEST_INTERVAL` | 0.2s | Minimum time between requests |
| `MAX_RETRIES` | 3 | Automatic retry attempts |
| `RETRY_DELAY` | 1.0s | Base delay between retries |
| `DEFAULT_CACHE_TTL` | 300s | Default cache lifetime (5 min) |
---
## Entity Types
### Supported Entity Types
The API supports 25+ entity types organized into categories:
#### Equipment & Items
| Entity Type | Endpoint | Description |
|-------------|----------|-------------|
| `items` | `/items` | General items and components |
| `weapons` | `/weapons` | Ranged and melee weapons |
| `armors` | `/armors` | Protective armor sets |
| `enhancers` | `/enhancers` | Weapon/armor enhancers |
#### Tools & Professional
| Entity Type | Endpoint | Description |
|-------------|----------|-------------|
| `medicaltools` | `/medicaltools` | First Aid Packs, healing tools |
| `finders` | `/finders` | Mining finders/detectors |
| `excavators` | `/excavators` | Mining excavators |
| `refiners` | `/refiners` | Resource refiners |
#### Crafting & Materials
| Entity Type | Endpoint | Description |
|-------------|----------|-------------|
| `blueprints` | `/blueprints` | Crafting recipes |
| `materials` | `/materials` | Raw materials, ores, enmatters |
#### Creatures & Characters
| Entity Type | Endpoint | Description |
|-------------|----------|-------------|
| `mobs` | `/mobs` | Creatures, monsters, NPCs |
| `pets` | `/pets` | Tameable companion creatures |
#### Locations & Places
| Entity Type | Endpoint | Description |
|-------------|----------|-------------|
| `locations` | `/locations` | Points of interest |
| `teleporters` | `/teleporters` | Teleporter locations |
| `shops` | `/shops` | Player shops |
| `vendors` | `/vendors` | NPC vendors |
| `planets` | `/planets` | Planet information |
| `areas` | `/areas` | Geographic regions |
#### Other
| Entity Type | Endpoint | Description |
|-------------|----------|-------------|
| `skills` | `/skills` | Player skills and professions |
| `vehicles` | `/vehicles` | Ships, cars, mounts |
| `decorations` | `/decorations` | Estate decorations |
| `furniture` | `/furniture` | Estate furniture |
| `storagecontainers` | `/storagecontainers` | Storage boxes |
| `strongboxes` | `/strongboxes` | Loot strongboxes |
---
## Endpoints
### Search Endpoints
#### Universal Search
```http
GET /search?q={query}&limit={limit}&fuzzy={true|false}
```
Search across all entity types simultaneously.
**Parameters:**
- `q` (required): Search query string
- `limit` (optional): Maximum results (default: 20, max: 100)
- `fuzzy` (optional): Enable fuzzy matching (default: false)
**Response:**
```json
[
{
"id": "armatrix-lp-35",
"name": "ArMatrix LP-35 (L)",
"type": "Weapon",
"category": "Laser Weapons",
"icon_url": "https://..."
}
]
```
#### Entity-Specific Search
```http
GET /{entity-type}?q={query}&limit={limit}&fuzzy={true|false}
```
Search within a specific entity type.
**Example:**
```http
GET /weapons?q=ArMatrix&limit=20&fuzzy=true
```
### Item Endpoints
#### Get Item Details
```http
GET /items/{item-id}
```
Retrieve detailed information about a specific item.
**Response:**
```json
{
"id": "armatrix-lp-35",
"name": "ArMatrix LP-35 (L)",
"description": "A powerful laser pistol...",
"category": "Laser Weapons",
"weight": 2.5,
"tt_value": 120.0,
"decay": 0.5,
"ammo_consumption": 10,
"damage": 45.0,
"range": 45.0,
"accuracy": 80.0,
"durability": 10000,
"requirements": {
"level": 25,
"profession": "Laser Sniper (Hit)"
},
"materials": [
{"name": "Lysterium Ingot", "amount": 50}
]
}
```
#### Get Market Data
```http
GET /items/{item-id}/market
```
Retrieve current market data for an item.
**Response:**
```json
{
"item_id": "armatrix-lp-35",
"item_name": "ArMatrix LP-35 (L)",
"current_markup": 115.5,
"avg_markup_7d": 112.3,
"avg_markup_30d": 113.8,
"volume_24h": 150,
"volume_7d": 1200,
"buy_orders": [
{"price": 138.6, "quantity": 5}
],
"sell_orders": [
{"price": 145.2, "quantity": 10}
],
"last_updated": "2025-02-13T10:30:00Z"
}
```
### Entity Detail Endpoints
All entity types support individual retrieval:
```http
GET /{entity-type}/{entity-id}
```
**Examples:**
```http
GET /mobs/atrox
GET /locations/fort-izzuk
GET /blueprints/armatrix-lp-35
GET /skills/rifle
```
### Market Data Endpoints (www.entropianexus.com)
**Note:** These endpoints use the `www.` subdomain, not `api.`
#### Exchange Listings
```http
GET https://www.entropianexus.com/api/market/exchange
```
**Response:**
```json
{
"categories": [
{
"name": "Weapons",
"items": [
{
"id": "item-id",
"name": "Item Name",
"type": "Weapon",
"buy": [{"price": 100.0, "quantity": 5}],
"sell": [{"price": 110.0, "quantity": 3}]
}
]
}
]
}
```
#### Latest Prices
```http
GET https://www.entropianexus.com/api/market/prices/latest?items={comma-separated-ids}
```
**Parameters:**
- `items`: Comma-separated list of item IDs (max 100)
---
## Request Parameters
### Common Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `q` | string | - | Search query |
| `query` | string | - | Alternative search parameter |
| `limit` | integer | 20 | Maximum results (max: 100) |
| `fuzzy` | boolean | false | Enable fuzzy matching |
| `type` | string | - | Filter by entity type |
### Filter Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `category` | string | Filter by category |
| `min_level` | integer | Minimum level requirement |
| `max_level` | integer | Maximum level requirement |
| `planet` | string | Filter by planet name |
### Pagination
| Parameter | Type | Description |
|-----------|------|-------------|
| `offset` | integer | Skip N results |
| `limit` | integer | Return N results |
---
## Response Formats
### Standard Response Structure
All API responses follow a consistent structure:
#### Search Result Item
```json
{
"id": "string", // Unique identifier
"name": "string", // Display name
"type": "string", // Entity type
"category": "string", // Category/classification
"icon_url": "string", // URL to icon image (optional)
// Type-specific fields below
}
```
### Type-Specific Response Fields
#### Weapons
```json
{
"id": "weapon-id",
"name": "Weapon Name",
"damage": 45.0, // Damage per shot
"range": 45.0, // Effective range in meters
"attacks": 45, // Attacks per minute
"ammo_consumption": 10, // Ammo per shot
"accuracy": 80.0, // Accuracy percentage
"decay": 0.5, // Decay per use (PED)
"durability": 10000 // Durability points
}
```
#### Armors
```json
{
"id": "armor-id",
"name": "Armor Name",
"protection": 25.0, // Protection value
"durability": 5000, // Durability points
"weight": 5.0 // Weight in kg
}
```
#### Mobs
```json
{
"id": "mob-id",
"name": "Mob Name",
"hitpoints": 1000, // HP
"damage": 50.0, // Damage range
"threat": "Medium", // Threat level
"planet": "Calypso",
"area": "Eastern Land
}
```
#### Locations
```json
{
"id": "loc-id",
"name": "Location Name",
"planet": "Calypso",
"x": 12345.0, // X coordinate
"y": 67890.0, // Y coordinate
"type": "Outpost"
}
```
#### Blueprints
```json
{
"id": "bp-id",
"name": "Blueprint Name",
"qr": 100.0, // Quality Rating max
"click": 1000, // Total clicks
"materials": [...], // Required materials
"product": {...} // Output item
}
```
#### Skills
```json
{
"id": "skill-id",
"name": "Skill Name",
"category": "Combat", // Skill category
"description": "..."
}
```
---
## Error Handling
### HTTP Status Codes
| Code | Meaning | Description |
|------|---------|-------------|
| 200 | OK | Request successful |
| 400 | Bad Request | Invalid parameters |
| 404 | Not Found | Entity not found |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Server Error | Internal server error |
| 502 | Bad Gateway | Upstream error |
| 503 | Service Unavailable | Temporarily unavailable |
### Error Response Format
```json
{
"error": "Error type",
"message": "Human-readable description",
"code": 404
}
```
### Exception Types (Python Client)
```python
class NexusAPIError(Exception):
"""Base exception for Nexus API errors."""
pass
class RateLimitError(NexusAPIError):
"""Raised when rate limit is exceeded."""
pass
```
### Error Handling Example
```python
from core.nexus_api import get_nexus_api, NexusAPIError, RateLimitError
api = get_nexus_api()
try:
details = api.get_item_details("invalid-id")
except RateLimitError as e:
print(f"Rate limited: {e}")
# Wait and retry
except NexusAPIError as e:
print(f"API error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
```
---
## Rate Limits
### Limits by Endpoint Type
| Endpoint Type | Limit | Window |
|---------------|-------|--------|
| General API | 5 requests | per second |
| Search | 10 requests | per minute |
| Market Data | 60 requests | per minute |
| Item Details | 30 requests | per minute |
### Rate Limit Headers
Responses include rate limit information:
```http
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1707832800
```
### Handling Rate Limits
```python
# The client automatically handles rate limiting
api = get_nexus_api()
# Built-in retry with exponential backoff
results = api.search_items("ArMatrix") # Auto-retries on 429
```
---
## Usage Examples
### Basic Search
```python
from core.nexus_api import get_nexus_api
api = get_nexus_api()
# Search for items
items = api.search_items("ArMatrix", limit=20)
for item in items:
print(f"{item.name} ({item.type})")
# Search for mobs
mobs = api.search_mobs("Atrox")
for mob in mobs:
print(f"{mob.name} - HP: {mob.data.get('hitpoints')}")
```
### Get Item Details
```python
# Get detailed information
details = api.get_item_details("armatrix-lp-35")
if details:
print(f"Name: {details.name}")
print(f"TT Value: {details.tt_value} PED")
print(f"Damage: {details.damage}")
print(f"Range: {details.range}m")
print(f"Decay: {details.decay} PED/use")
```
### Market Analysis
```python
# Get market data
market = api.get_market_data("armatrix-lp-35")
if market:
print(f"Current markup: {market.current_markup:.1f}%")
print(f"7-day average: {market.avg_markup_7d:.1f}%")
print(f"24h Volume: {market.volume_24h}")
# Check buy orders
for order in market.buy_orders[:5]:
print(f"Buy: {order['price']} PED x {order['quantity']}")
```
### Batch Operations
```python
# Get multiple items efficiently
item_ids = ["armatrix-lp-35", "armatrix-bp-25", "armatrix-sb-10"]
results = api.get_items_batch(item_ids)
for item_id, details in results.items():
if details:
print(f"{details.name}: {details.damage} dmg")
```
### Universal Search (All Entity Types)
```python
# Search across all types
results = api.search_all("Calypso", limit=30)
for result in results:
print(f"{result.name} [{result.type}]")
```
---
## Plugin API Integration
### Accessing Nexus API from Plugins
Plugins access the Nexus API through the PluginAPI:
```python
from plugins.base_plugin import BasePlugin
class MyPlugin(BasePlugin):
def search_item(self, query):
# Use the built-in nexus_search method
results = self.nexus_search(query, entity_type="items")
return results
def get_item_info(self, item_id):
# Get item details
details = self.nexus_get_item_details(item_id)
return details
def check_market(self, item_id):
# Get market data
market = self.nexus_get_market_data(item_id)
return market
```
### Available Plugin Methods
| Method | Description |
|--------|-------------|
| `nexus_search(query, entity_type)` | Search for entities |
| `nexus_get_item_details(item_id)` | Get item details |
| `nexus_get_market_data(item_id)` | Get market data |
### Entity Types for Plugins
```python
# Valid entity types for nexus_search()
entity_types = [
"items", "weapons", "armors", "blueprints", "mobs",
"locations", "skills", "materials", "enhancers",
"medicaltools", "finders", "excavators", "refiners",
"vehicles", "pets", "decorations", "furniture",
"storagecontainers", "strongboxes", "teleporters",
"shops", "vendors", "planets", "areas"
]
```
### Plugin Example: Weapon Finder
```python
from plugins.base_plugin import BasePlugin
class WeaponFinderPlugin(BasePlugin):
name = "Weapon Finder"
def find_weapons_by_damage(self, min_damage):
"""Find all weapons with minimum damage."""
# Search for weapons
results = self.nexus_search("", entity_type="weapons")
weapons = []
for weapon in results:
details = self.nexus_get_item_details(weapon.id)
if details and details.damage >= min_damage:
weapons.append(details)
return sorted(weapons, key=lambda w: w.damage, reverse=True)
```
---
## Field Name Conventions
### Important: Dual Naming Conventions
The API may return field names in **either** format:
- **snake_case**: `item_id`, `tt_value`, `current_markup`
- **PascalCase**: `ItemId`, `TTValue`, `CurrentMarkup`
### Handling Both Formats
```python
# Safe field access pattern
def get_field(data, *names, default=None):
"""Get field value trying multiple name variants."""
for name in names:
if name in data:
return data[name]
return default
# Usage
name = get_field(item, 'name', 'Name')
tt_value = get_field(item, 'tt_value', 'TTValue', 'TtValue')
damage = get_field(item, 'damage', 'Damage')
```
### Common Field Mappings
| Concept | snake_case | PascalCase |
|---------|------------|------------|
| ID | `id` | `Id` |
| Name | `name` | `Name` |
| Type | `type` | `Type` |
| Category | `category` | `Category` |
| TT Value | `tt_value` | `TTValue` |
| Damage | `damage` | `Damage` |
| Range | `range` | `Range` |
| Decay | `decay` | `Decay` |
| Weight | `weight` | `Weight` |
| Hitpoints | `hitpoints` | `Hitpoints` |
| Level | `level` | `Level` |
| Description | `description` | `Description` |
---
## Data Classes Reference
### SearchResult
```python
@dataclass
class SearchResult:
id: str # Entity ID
name: str # Display name
type: str # Entity type
category: str # Category (optional)
icon_url: str # Icon URL (optional)
data: dict # Raw response data
```
### ItemDetails
```python
@dataclass
class ItemDetails:
id: str
name: str
description: str
category: str
weight: float
tt_value: float
decay: float
ammo_consumption: int
damage: float
range: float
accuracy: float
durability: int
requirements: dict
materials: list
raw_data: dict
```
### MarketData
```python
@dataclass
class MarketData:
item_id: str
item_name: str
current_markup: float
avg_markup_7d: float
avg_markup_30d: float
volume_24h: int
volume_7d: int
buy_orders: list
sell_orders: list
last_updated: datetime
raw_data: dict
```
---
## Changelog
### v1.0 (2025-02-13)
- Initial complete API documentation
- Documented all 25+ entity types
- Added field naming convention notes
- Added Plugin API integration examples
---
## Related Files
- [NEXUS_LINKTREE.md](./NEXUS_LINKTREE.md) - URL reference
- [../core/nexus_api.py](../core/nexus_api.py) - API client implementation
- [../core/plugin_api.py](../core/plugin_api.py) - Plugin integration
- [../plugins/universal_search/plugin.py](../plugins/universal_search/plugin.py) - Usage example