Skip to content

API Reference

Vincent Perrin edited this page Jan 19, 2026 · 1 revision

🔌 API Reference

Complete reference for the Decompression Calculator backend API.

Table of Contents

  1. Overview
  2. Authentication
  3. Endpoints
  4. Data Models
  5. Error Handling
  6. Rate Limiting
  7. Examples

Overview

Base URL

Development:

http://localhost:3001/api

Production:

https://your-domain.com/api

API Version

Current version: v1

Content Type

All requests and responses use JSON:

Content-Type: application/json

CORS

The API supports CORS for allowed origins configured in environment variables.


Authentication

Currently, the API does not require authentication for most endpoints. Diver information is stored locally with optional encryption.

Future Authentication

Planned authentication methods:

  • JWT tokens
  • OAuth 2.0
  • API keys

Endpoints

Diver Information

Save Diver Information

Store encrypted diver information on the server.

Endpoint:

POST /api/diver-info

Request Body:

{
  "firstName": "John",
  "lastName": "Doe",
  "phoneNumber": "+1234567890",
  "padiNumber": "1234567",
  "emergencyContact": {
    "name": "Jane Doe",
    "phone": "+1234567891"
  }
}

Validation Rules:

  • firstName: 1-50 characters, alphanumeric
  • lastName: 1-50 characters, alphanumeric
  • phoneNumber: Valid phone format
  • padiNumber: 1-20 characters
  • All fields are sanitized for XSS

Response (200 OK):

{
  "success": true,
  "message": "Diver information saved successfully"
}

Response (400 Bad Request):

{
  "success": false,
  "errors": [
    {
      "field": "firstName",
      "message": "First name is required"
    }
  ]
}

Rate Limit: 10 requests per 15 minutes


Get Diver Information

Retrieve stored diver information.

Endpoint:

GET /api/diver-info

Response (200 OK):

{
  "success": true,
  "data": {
    "firstName": "John",
    "lastName": "Doe",
    "phoneNumber": "+1234567890",
    "padiNumber": "1234567",
    "emergencyContact": {
      "name": "Jane Doe",
      "phone": "+1234567891"
    }
  }
}

Response (404 Not Found):

{
  "success": false,
  "message": "No diver information found"
}

Rate Limit: 100 requests per 15 minutes


Delete Diver Information

Remove stored diver information.

Endpoint:

DELETE /api/diver-info

Response (200 OK):

{
  "success": true,
  "message": "Diver information deleted successfully"
}

Response (404 Not Found):

{
  "success": false,
  "message": "No diver information found"
}

Rate Limit: 10 requests per 15 minutes


Weather Service

Get Weather Data

Retrieve weather information for dive site coordinates.

Endpoint:

GET /api/weather

Query Parameters:

  • lat (required): Latitude (-90 to 90)
  • lon (required): Longitude (-180 to 180)

Example:

GET /api/weather?lat=43.7384&lon=7.4246

Response (200 OK):

{
  "success": true,
  "data": {
    "temperature": 22.5,
    "conditions": "Clear",
    "windSpeed": 5.2,
    "windDirection": "NE",
    "waveHeight": 0.5,
    "visibility": 10,
    "pressure": 1013,
    "humidity": 65,
    "timestamp": "2026-01-19T11:00:00Z"
  }
}

Response (400 Bad Request):

{
  "success": false,
  "message": "Invalid coordinates"
}

Rate Limit: 60 requests per hour


Health Check

Server Health

Check if the API server is running.

Endpoint:

GET /api/health

Response (200 OK):

{
  "status": "healthy",
  "timestamp": "2026-01-19T11:00:00Z",
  "uptime": 3600,
  "version": "1.0.0"
}

Data Models

DiverInfo

interface DiverInfo {
  firstName: string;        // 1-50 characters
  lastName: string;         // 1-50 characters
  phoneNumber: string;      // Valid phone format
  padiNumber: string;       // 1-20 characters
  emergencyContact?: {
    name: string;
    phone: string;
  };
  certificationLevel?: string;
  medicalClearance?: boolean;
  lastDiveDate?: string;    // ISO 8601 date
}

WeatherData

interface WeatherData {
  temperature: number;      // Celsius
  conditions: string;       // Description
  windSpeed: number;        // m/s
  windDirection: string;    // Cardinal direction
  waveHeight: number;       // meters
  visibility: number;       // kilometers
  pressure: number;         // hPa
  humidity: number;         // percentage
  timestamp: string;        // ISO 8601
}

ErrorResponse

interface ErrorResponse {
  success: false;
  message: string;
  errors?: Array<{
    field: string;
    message: string;
  }>;
  code?: string;
}

SuccessResponse

interface SuccessResponse<T> {
  success: true;
  data?: T;
  message?: string;
}

Error Handling

HTTP Status Codes

Code Meaning Description
200 OK Request successful
201 Created Resource created
400 Bad Request Invalid input
401 Unauthorized Authentication required
403 Forbidden Access denied
404 Not Found Resource not found
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Server error
503 Service Unavailable Server maintenance

Error Response Format

All errors follow this format:

{
  "success": false,
  "message": "Human-readable error message",
  "errors": [
    {
      "field": "fieldName",
      "message": "Field-specific error"
    }
  ],
  "code": "ERROR_CODE"
}

Common Error Codes

Code Description
VALIDATION_ERROR Input validation failed
NOT_FOUND Resource not found
RATE_LIMIT_EXCEEDED Too many requests
INTERNAL_ERROR Server error
INVALID_REQUEST Malformed request

Rate Limiting

Limits by Endpoint

Endpoint Limit Window
POST /api/diver-info 10 15 minutes
GET /api/diver-info 100 15 minutes
DELETE /api/diver-info 10 15 minutes
GET /api/weather 60 1 hour
GET /api/health 1000 15 minutes

Rate Limit Headers

Responses include rate limit information:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1642598400

Rate Limit Exceeded Response

{
  "success": false,
  "message": "Rate limit exceeded. Please try again later.",
  "code": "RATE_LIMIT_EXCEEDED",
  "retryAfter": 900
}

Examples

JavaScript/TypeScript

Save Diver Information

async function saveDiverInfo(info: DiverInfo) {
  try {
    const response = await fetch('http://localhost:3001/api/diver-info', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(info),
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message);
    }

    const result = await response.json();
    console.log('Success:', result.message);
    return result;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

// Usage
const diverInfo = {
  firstName: 'John',
  lastName: 'Doe',
  phoneNumber: '+1234567890',
  padiNumber: '1234567',
};

saveDiverInfo(diverInfo);

Get Weather Data

async function getWeather(lat: number, lon: number) {
  try {
    const response = await fetch(
      `http://localhost:3001/api/weather?lat=${lat}&lon=${lon}`
    );

    if (!response.ok) {
      throw new Error('Failed to fetch weather data');
    }

    const result = await response.json();
    return result.data;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

// Usage
const weather = await getWeather(43.7384, 7.4246);
console.log('Temperature:', weather.temperature);

cURL Examples

Save Diver Information

curl -X POST http://localhost:3001/api/diver-info \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "phoneNumber": "+1234567890",
    "padiNumber": "1234567"
  }'

Get Diver Information

curl http://localhost:3001/api/diver-info

Get Weather Data

curl "http://localhost:3001/api/weather?lat=43.7384&lon=7.4246"

Delete Diver Information

curl -X DELETE http://localhost:3001/api/diver-info

Python Example

import requests

# Save diver information
def save_diver_info(info):
    url = 'http://localhost:3001/api/diver-info'
    headers = {'Content-Type': 'application/json'}
    
    response = requests.post(url, json=info, headers=headers)
    
    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"Error: {response.json()['message']}")

# Usage
diver_info = {
    'firstName': 'John',
    'lastName': 'Doe',
    'phoneNumber': '+1234567890',
    'padiNumber': '1234567'
}

result = save_diver_info(diver_info)
print(result['message'])

Security

Input Validation

All inputs are validated and sanitized:

  • XSS protection via escaping
  • SQL injection prevention (when applicable)
  • Length limits enforced
  • Type checking

HTTPS

Production environments must use HTTPS.

Headers

Security headers are automatically added:

X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000

Data Encryption

Sensitive data (diver information) is encrypted at rest using AES-256.


Webhooks (Future)

Planned Webhook Events

  • dive.calculated - When a dive profile is calculated
  • diver.updated - When diver information is updated
  • weather.alert - When weather conditions change

Webhook Payload Format

{
  "event": "dive.calculated",
  "timestamp": "2026-01-19T11:00:00Z",
  "data": {
    "depth": 30,
    "time": 25,
    "totalDiveTime": 45
  }
}

API Versioning

Current Version

All endpoints are currently v1 (implicit).

Future Versions

When v2 is released, endpoints will be:

/api/v2/diver-info
/api/v2/weather

v1 will be maintained for backward compatibility.


SDK Support

Official SDKs (Planned)

  • JavaScript/TypeScript
  • Python
  • Go

Community SDKs

Check the GitHub repository for community-contributed SDKs.


Testing the API

Using Postman

  1. Import the Postman Collection
  2. Set environment variables
  3. Run requests

Using Insomnia

  1. Import the Insomnia Workspace
  2. Configure base URL
  3. Test endpoints

Automated Testing

# Run API tests
npm run test:api

# Run integration tests
npm run test:integration

Monitoring

Health Checks

Monitor API health:

curl http://localhost:3001/api/health

Metrics (Future)

Planned metrics endpoints:

  • /api/metrics - Prometheus metrics
  • /api/stats - Usage statistics

Support

Issues

Report API issues on GitHub Issues

Documentation Updates

API documentation is versioned with the codebase. Submit PRs for improvements.


Changelog

v1.0.0 (Current)

  • Initial API release
  • Diver information endpoints
  • Weather service integration
  • Rate limiting
  • Security middleware

Upcoming

  • Authentication system
  • Webhook support
  • Batch operations
  • GraphQL endpoint

Next: Deployment Guide - Deploy to production

Previous: Developer Guide - Development documentation

Clone this wiki locally