# Nyx API Documentation

> Complete guide to the Nyx Astronomy API

The Nyx API provides programmatic access to astronomical data, ephemeris
calculations, celestial events, and satellite tracking. This documentation
covers all aspects of integrating with the Nyx API.

## Table of Contents

### Getting Started

- [Overview](#overview)
- [Base URL](#base-url)
- [Quick Start](#quick-start)

### API Guides

1. [REST API Usage](./rest-api.md) - Complete REST endpoint reference
2. [WebSocket Integration](./websocket.md) - Real-time data streaming
3. [Widget Embedding](./widgets.md) - Embed Nyx components in your apps
4. [Authentication](./authentication.md) - API keys and access control

### Reference

- [Response Formats](#response-formats)
- [Error Handling](#error-handling)
- [Rate Limits](#rate-limits)
- [SDKs and Libraries](#sdks-and-libraries)

---

## Overview

The Nyx API is a comprehensive astronomy REST API with WebSocket support,
providing:

- **Celestial Object Catalog**: Access to stars, planets, galaxies, nebulae, and
  deep sky objects from multiple catalogs (Messier, NGC, Hipparcos, Gaia)
- **Ephemeris Calculations**: High-precision position calculations for solar
  system objects with observer-specific coordinates
- **Astronomical Events**: Eclipses, conjunctions, meteor showers, moon phases,
  and other celestial events
- **Satellite Tracking**: Real-time positions and pass predictions for ISS and
  other satellites

### API Version

Current version: **v1**

All endpoints are prefixed with `/api/v1/`.

### Technology Stack

- Built on Hono (edge-first web framework)
- OpenAPI 3.1.0 specification
- WebSocket support for real-time updates
- RFC 7807 compliant error responses

---

## Base URL

| Environment | Base URL                           |
| ----------- | ---------------------------------- |
| Production  | `https://api.nyx.oshun.io`         |
| Staging     | `https://staging-api.nyx.oshun.io` |
| Development | `http://localhost:3000`            |

---

## Quick Start

### 1. Get an API Key

Register at [nyx.oshun.io/developers](https://nyx.oshun.io/developers) to get
your API key.

For testing, you can use the demo key: `nyx_free_demo123456`

### 2. Make Your First Request

```bash
# Get upcoming astronomical events
curl -H "X-API-Key: nyx_free_demo123456" \
  "https://api.nyx.oshun.io/api/v1/events/upcoming"
```

### 3. Explore the API

Interactive documentation is available at:

- Swagger UI: `/api/docs`
- OpenAPI spec: `/api/v1/openapi.json`

---

## Quick Examples

### Search for Celestial Objects

```bash
curl "https://api.nyx.oshun.io/api/v1/objects/search?q=orion"
```

### Get Planet Position

```bash
curl -H "X-API-Key: YOUR_API_KEY" \
  "https://api.nyx.oshun.io/api/v1/ephemeris?objectId=mars&latitude=40.7128&longitude=-74.0060"
```

### Get ISS Pass Predictions

```bash
curl -H "X-API-Key: YOUR_API_KEY" \
  "https://api.nyx.oshun.io/api/v1/satellites/25544/passes?latitude=40.7128&longitude=-74.0060&days=7"
```

### Subscribe to Real-Time Updates

```javascript
const ws = new WebSocket('wss://api.nyx.oshun.io/ws');

ws.onopen = () => {
  // Authenticate
  ws.send(
    JSON.stringify({
      type: 'auth',
      payload: { apiKey: 'YOUR_API_KEY' },
    })
  );

  // Subscribe to ISS position updates
  ws.send(
    JSON.stringify({
      type: 'subscribe',
      payload: {
        channel: 'satellites:25544',
        options: { updateInterval: 1000 },
      },
    })
  );
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('ISS position:', data);
};
```

---

## Response Formats

### Success Response

All successful responses follow this structure:

```json
{
  "success": true,
  "data": {
    // Response data here
  },
  "meta": {
    "requestId": "req_abc123",
    "timestamp": "2026-01-21T12:00:00.000Z"
  }
}
```

### Paginated Response

List endpoints include pagination:

```json
{
  "success": true,
  "data": [...],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 150,
    "totalPages": 8,
    "hasNext": true,
    "hasPrev": false
  },
  "meta": {
    "requestId": "req_abc123",
    "timestamp": "2026-01-21T12:00:00.000Z"
  }
}
```

---

## Error Handling

Errors follow RFC 7807 Problem Details format:

```json
{
  "type": "https://api.nyx.io/problems/validation-error",
  "title": "Validation Error",
  "status": 400,
  "detail": "The request parameters failed validation.",
  "instance": "/api/v1/ephemeris",
  "requestId": "req_abc123",
  "timestamp": "2026-01-21T12:00:00.000Z",
  "code": "VALIDATION_ERROR",
  "errors": [
    {
      "path": "latitude",
      "message": "Must be between -90 and 90",
      "code": "invalid_range"
    }
  ]
}
```

### HTTP Status Codes

| Code | Meaning               | Description                       |
| ---- | --------------------- | --------------------------------- |
| 200  | OK                    | Request succeeded                 |
| 400  | Bad Request           | Invalid input parameters          |
| 401  | Unauthorized          | Missing or invalid API key        |
| 403  | Forbidden             | Insufficient permissions for tier |
| 404  | Not Found             | Resource not found                |
| 429  | Too Many Requests     | Rate limit exceeded               |
| 500  | Internal Server Error | Server error                      |
| 503  | Service Unavailable   | Service temporarily unavailable   |

---

## Rate Limits

Rate limits are based on your API key tier:

| Tier       | Requests/Minute | Burst Limit |
| ---------- | --------------- | ----------- |
| Anonymous  | 60              | 10          |
| Free       | 300             | 30          |
| Pro        | 1,000           | 100         |
| Enterprise | 5,000           | 500         |

### Rate Limit Headers

Every response includes rate limit information:

```
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 287
X-RateLimit-Reset: 1705334445
X-RateLimit-Tier: free
```

### Handling Rate Limits

When rate limited, you'll receive a 429 response with a `Retry-After` header:

```json
{
  "type": "https://api.nyx.io/problems/rate-limit-exceeded",
  "title": "Rate Limit Exceeded",
  "status": 429,
  "detail": "You have exceeded the rate limit of 300 requests per minute.",
  "code": "RATE_LIMIT_EXCEEDED",
  "limit": 300,
  "remaining": 0,
  "resetAt": 1705334445
}
```

---

## SDKs and Libraries

### Official SDKs

| Language   | Package                   | Install                          |
| ---------- | ------------------------- | -------------------------------- |
| JavaScript | `@nyx/api-client`         | `npm install @nyx/api-client`    |
| Python     | `nyx-api`                 | `pip install nyx-api`            |
| Go         | `github.com/oshun/nyx-go` | `go get github.com/oshun/nyx-go` |
| Rust       | `nyx-api`                 | `cargo add nyx-api`              |

### JavaScript SDK Example

```typescript
import { NyxClient } from '@nyx/api-client';

const client = new NyxClient({
  apiKey: 'YOUR_API_KEY',
});

// Get Mars position
const position = await client.ephemeris.getPosition('mars', {
  latitude: 40.7128,
  longitude: -74.006,
});

console.log(`Mars is at RA: ${position.ra}, Dec: ${position.dec}`);
```

### Python SDK Example

```python
from nyx_api import NyxClient

client = NyxClient(api_key='YOUR_API_KEY')

# Search for objects
objects = client.objects.search('orion nebula')
for obj in objects:
    print(f"{obj.name}: {obj.magnitude} mag")

# Get ISS passes
passes = client.satellites.get_passes(
    satellite_id='25544',
    latitude=40.7128,
    longitude=-74.0060
)
```

---

## API Endpoints Summary

### Objects

| Endpoint                     | Description            |
| ---------------------------- | ---------------------- |
| `GET /api/v1/objects`        | List celestial objects |
| `GET /api/v1/objects/search` | Search objects by name |
| `GET /api/v1/objects/{id}`   | Get object details     |

### Ephemeris

| Endpoint                         | Description            |
| -------------------------------- | ---------------------- |
| `GET /api/v1/ephemeris`          | Calculate positions    |
| `GET /api/v1/ephemeris/position` | Current position       |
| `GET /api/v1/ephemeris/rise-set` | Rise/transit/set times |

### Events

| Endpoint                      | Description              |
| ----------------------------- | ------------------------ |
| `GET /api/v1/events`          | List astronomical events |
| `GET /api/v1/events/upcoming` | Next 7 days of events    |
| `GET /api/v1/events/types`    | List event types         |
| `GET /api/v1/events/{id}`     | Get event details        |

### Satellites

| Endpoint                             | Description           |
| ------------------------------------ | --------------------- |
| `GET /api/v1/satellites`             | List satellites       |
| `GET /api/v1/satellites/categories`  | List categories       |
| `GET /api/v1/satellites/passes`      | Pass predictions      |
| `GET /api/v1/satellites/{id}`        | Get satellite details |
| `GET /api/v1/satellites/{id}/passes` | Passes for satellite  |

### WebSocket

| Endpoint | Description              |
| -------- | ------------------------ |
| `/ws`    | Real-time data streaming |

---

## Support

- **Documentation**: You're here!
- **API Status**: [status.nyx.oshun.io](https://status.nyx.oshun.io)
- **GitHub Issues**:
  [github.com/oshun/nyx/issues](https://github.com/oshun/nyx/issues)
- **Email**: api-support@nyx.oshun.io

---

## Next Steps

- [REST API Reference](./rest-api.md) - Complete endpoint documentation
- [WebSocket Integration](./websocket.md) - Real-time data streaming
- [Authentication](./authentication.md) - API key management
