AthlEAT
Guide

Configuration

Environment variables, config files, feature flags


Overview

This page explains how to configure the athlete-nutrition-ai API for your environment, covering environment variables, configuration files, and feature flags. Proper configuration controls how the service authenticates requests, connects to backing services, and exposes optional capabilities such as AI advisor features and subscription management. Whether you are setting up a local development environment or deploying to production, this guide walks you through every option you need to get the API running correctly. Understanding these settings upfront will help you avoid common integration errors and tune the service to match your application's requirements.


Prerequisites

Before configuring the athlete-nutrition-ai API, make sure you have the following in place:

  • An active API account — You must have completed account registration and received your API credentials. See the Authentication guide for details.
  • API key and client secret — Available in your developer dashboard after account creation.
  • HTTP client or SDK — Any tool capable of making HTTP requests (e.g., curl, Postman, or a language-specific HTTP library).
  • Node.js 18+ or Python 3.10+ (if using an official SDK) — Refer to the SDK README for language-specific minimums.
  • A .env-compatible environment — The API client and any companion tooling read configuration from environment variables or a .env file at the project root.
  • Access to a training calendar endpoint or iCal feed (optional at setup, required for the calendar-sync workflow) — Needed before calling the training-event or meal-plan generation endpoints.

Installation

Follow these steps to install and initialize the athlete-nutrition-ai client in your project.

Step 1 — Install the client library

Choose the package manager for your environment:

# npm
npm install athlete-nutrition-ai

# yarn
yarn add athlete-nutrition-ai

# pip (Python SDK)
pip install athlete-nutrition-ai

Step 2 — Create a configuration file

Copy the example environment file included with the package to your project root:

cp node_modules/athlete-nutrition-ai/.env.example .env

For Python:

cp $(pip show athlete-nutrition-ai | grep Location | awk '{print $2}')/athlete_nutrition_ai/.env.example .env

Step 3 — Populate required credentials

Open .env in your editor and set the minimum required values:

ATHLETE_NUTRITION_API_KEY=your_api_key_here
ATHLETE_NUTRITION_API_SECRET=your_client_secret_here
ATHLETE_NUTRITION_BASE_URL=https://api.athlete-nutrition-ai.com/v1

Step 4 — Verify the connection

Run the built-in health-check command to confirm your credentials and network access are working:

# Node.js
npx athlete-nutrition-ai healthcheck

# Python
python -m athlete_nutrition_ai healthcheck

Expected output on success:

✔ Connection established
✔ Credentials valid
✔ API version: v1
Status: OK

If you see an error, consult the Troubleshooting section below.


Configuration

All configuration is supplied through environment variables. You can set these directly in your shell, in a .env file at your project root, or through your deployment platform's secrets manager. Values in .env are loaded automatically by the SDK; for direct HTTP integrations you must export them yourself.


Authentication

VariableRequiredDefaultDescription
ATHLETE_NUTRITION_API_KEY✅ YesYour public API key, included as the X-API-Key header on every request.
ATHLETE_NUTRITION_API_SECRET✅ YesYour client secret, used to sign request tokens. Never expose this in client-side code.

API Connection

VariableRequiredDefaultValid ValuesDescription
ATHLETE_NUTRITION_BASE_URL✅ YesAny valid HTTPS URLThe root URL of the API. Use the production URL for live deployments; point to a staging URL during testing.
ATHLETE_NUTRITION_TIMEOUT_MSNo10000Integer ≥ 1000Request timeout in milliseconds. Increase this value if you are generating large meal plans or shopping lists, which can take longer to compute.
ATHLETE_NUTRITION_MAX_RETRIESNo3Integer 0–10Number of automatic retries on transient 5xx errors. Set to 0 to disable retries entirely.

Athlete Profile & Data

VariableRequiredDefaultValid ValuesDescription
ATHLETE_NUTRITION_DEFAULT_UNITSNometricmetric, imperialDefault unit system for weight, distance, and nutrition values returned by the API. Can be overridden per-request with the units query parameter.
ATHLETE_NUTRITION_DEFAULT_LOCALENoen-USBCP 47 locale tagControls the language and regional formatting of generated meal plan text and shopping list labels.

Calendar Integration

VariableRequiredDefaultValid ValuesDescription
ATHLETE_NUTRITION_CALENDAR_SYNC_INTERVALNo3600Integer (seconds)How often the API client polls for training event updates when using continuous-sync mode. Lower values increase freshness but raise your API request count.

Feature Flags

Feature flags let you opt in to beta capabilities or restrict which features are active in a given environment.

VariableRequiredDefaultValid ValuesDescription
ATHLETE_NUTRITION_FEATURE_AI_ADVISORNotruetrue, falseEnables the AI nutrition advisor chat endpoint. Disable in environments where LLM costs must be minimized or where the feature is not yet approved for use.
ATHLETE_NUTRITION_FEATURE_SHOPPING_LISTNotruetrue, falseEnables the shopping list generation endpoint. Disable if your integration does not use this workflow.
ATHLETE_NUTRITION_FEATURE_SUBSCRIPTION_MGMTNotruetrue, falseEnables subscription management endpoints. Set to false in staging environments to avoid accidental billing mutations.

Logging & Observability

VariableRequiredDefaultValid ValuesDescription
ATHLETE_NUTRITION_LOG_LEVELNowarnerror, warn, info, debugControls SDK-side log verbosity. Use debug during development to see full request/response payloads; use warn or error in production to reduce noise.
ATHLETE_NUTRITION_LOG_REQUESTSNofalsetrue, falseWhen true, the SDK logs every outbound HTTP request URL and status code. Useful for auditing but may expose sensitive path parameters in logs.

Usage

Once your environment variables are set, you interact with athlete-nutrition-ai by making authenticated HTTP requests to the configured BASE_URL. The sections below show the most common patterns you will follow.


Setting credentials for direct HTTP requests

If you are calling the API without the SDK, include your API key in every request header:

curl -X GET "https://api.athlete-nutrition-ai.com/v1/profile" \
  -H "X-API-Key: $ATHLETE_NUTRITION_API_KEY" \
  -H "Content-Type: application/json"

The X-API-Key header is required on every request. Requests without it return 401 Unauthorized.


Using the SDK with environment variables

The SDK automatically reads from your .env file, so initialization requires no explicit credential passing:

// Node.js
import { NutritionClient } from 'athlete-nutrition-ai';

// Credentials are loaded from ATHLETE_NUTRITION_API_KEY and
// ATHLETE_NUTRITION_API_SECRET environment variables automatically.
const client = new NutritionClient();
# Python
from athlete_nutrition_ai import NutritionClient

# Same automatic loading behaviour.
client = NutritionClient()

Overriding configuration at runtime

You can override any environment variable setting by passing options directly to the client constructor. This is useful when you need to direct traffic to a staging environment from within a single codebase:

const stagingClient = new NutritionClient({
  baseUrl: 'https://staging-api.athlete-nutrition-ai.com/v1',
  timeoutMs: 20000,
  features: {
    aiAdvisor: true,
    subscriptionManagement: false  // keep billing mutations off in staging
  }
});

Switching unit systems per request

Even if ATHLETE_NUTRITION_DEFAULT_UNITS is set to metric, you can override it for individual calls using the units query parameter:

curl -X GET "https://api.athlete-nutrition-ai.com/v1/meal-plan?units=imperial" \
  -H "X-API-Key: $ATHLETE_NUTRITION_API_KEY"

Disabling a feature flag in production

To turn off AI advisor calls in a production deployment where costs must be controlled, set the flag before starting your application:

export ATHLETE_NUTRITION_FEATURE_AI_ADVISOR=false
node server.js

Any request to the advisor endpoint while this flag is false will receive a 403 Forbidden response with the error code FEATURE_DISABLED.


Examples

The examples below are self-contained and assume your environment variables are already exported.


Example 1 — Verify configuration with a health check

curl -X GET "https://api.athlete-nutrition-ai.com/v1/health" \
  -H "X-API-Key: $ATHLETE_NUTRITION_API_KEY"

Expected response (200 OK):

{
  "status": "ok",
  "apiVersion": "v1",
  "features": {
    "aiAdvisor": true,
    "shoppingList": true,
    "subscriptionManagement": true
  }
}

The features object reflects the server-side state of your feature flags. If a flag you set locally does not appear as you expect, confirm the variable name and value are being passed to the process.


Example 2 — Fetch an athlete profile using the Node.js SDK with debug logging

export ATHLETE_NUTRITION_LOG_LEVEL=debug
export ATHLETE_NUTRITION_LOG_REQUESTS=true
import { NutritionClient } from 'athlete-nutrition-ai';

const client = new NutritionClient();
const profile = await client.athlete.getProfile('athlete_abc123');
console.log(profile);

Expected console output (debug logging active):

[DEBUG] GET https://api.athlete-nutrition-ai.com/v1/athlete/athlete_abc123 → 200
{
  id: 'athlete_abc123',
  name: 'Jordan Lee',
  units: 'metric',
  dietaryPreferences: ['gluten-free'],
  createdAt: '2024-03-15T09:00:00Z'
}

Example 3 — Generate a meal plan in imperial units with a custom timeout

from athlete_nutrition_ai import NutritionClient

client = NutritionClient(timeout_ms=20000)

meal_plan = client.meal_plans.generate(
    athlete_id="athlete_abc123",
    event_ids=["event_789", "event_790"],
    units="imperial"
)

print(meal_plan)

Expected output:

{
  "mealPlanId": "mp_x1y2z3",
  "athleteId": "athlete_abc123",
  "units": "imperial",
  "generatedAt": "2024-06-01T07:30:00Z",
  "days": [
    {
      "date": "2024-06-02",
      "meals": [
        { "name": "Pre-race breakfast", "calories": 620, "carbsG": 95 }
      ]
    }
  ]
}

Example 4 — Confirm a feature flag is disabled before calling the AI advisor

import { NutritionClient } from 'athlete-nutrition-ai';

const client = new NutritionClient();
const health = await client.health.check();

if (!health.features.aiAdvisor) {
  console.warn('AI Advisor feature is disabled. Set ATHLETE_NUTRITION_FEATURE_AI_ADVISOR=true to enable.');
} else {
  const reply = await client.advisor.chat({
    athleteId: 'athlete_abc123',
    message: 'What should I eat the morning before a half marathon?'
  });
  console.log(reply.text);
}

Expected output when flag is disabled:

AI Advisor feature is disabled. Set ATHLETE_NUTRITION_FEATURE_AI_ADVISOR=true to enable.

Troubleshooting

Use the table below to diagnose the most common configuration-related failures. Each issue follows the pattern: Symptom → Likely Cause → Fix.


Issue: 401 Unauthorized on every request

  • Symptom: All API calls return HTTP 401 with an error body like { "error": "invalid_credentials" }.
  • Likely cause: ATHLETE_NUTRITION_API_KEY is missing, empty, or contains extra whitespace/quotes copied from a dashboard.
  • Fix: Print the variable to confirm its value (echo $ATHLETE_NUTRITION_API_KEY). Re-copy the key from your developer dashboard, ensure there are no surrounding quotes in your .env file, and restart your process so the new value is loaded.

Issue: 403 Forbidden with error code FEATURE_DISABLED

  • Symptom: A specific endpoint returns HTTP 403 and the response body contains "code": "FEATURE_DISABLED".
  • Likely cause: The corresponding feature flag environment variable (e.g., ATHLETE_NUTRITION_FEATURE_AI_ADVISOR) is set to false.
  • Fix: Set the flag to true in your .env file or shell, then restart the process. If you are in a deployment environment, update the secret or environment variable in your platform's configuration panel.

Issue: Requests time out on meal plan or shopping list generation

  • Symptom: The SDK throws a timeout error or curl hangs and eventually exits for calls to /meal-plan or /shopping-list.
  • Likely cause: ATHLETE_NUTRITION_TIMEOUT_MS is set too low (default 10000 ms) for computationally intensive operations.
  • Fix: Increase the timeout. For meal plan and shopping list endpoints, a value of 3000060000 ms is recommended. Set ATHLETE_NUTRITION_TIMEOUT_MS=30000 in your .env file and test again.

Issue: Unit system in responses does not match what I configured

  • Symptom: Response payloads use metric values even though ATHLETE_NUTRITION_DEFAULT_UNITS=imperial is set.
  • Likely cause 1: The environment variable was set after the SDK was initialized. The SDK reads variables at startup.
  • Likely cause 2: A per-request units query parameter in your code is overriding the default.
  • Fix: Ensure the variable is exported before the process starts. Search your codebase for hardcoded units parameters that may be taking precedence.

Issue: .env file is not being read

  • Symptom: Configuration values are not applied even though they appear correct in .env.
  • Likely cause: The .env file is in the wrong directory, or your runtime does not auto-load it.
  • Fix: Confirm the file is in the same directory from which you launch your application. For Node.js projects not using the SDK, add a dotenv loader: import 'dotenv/config'; at the top of your entry file. For Python, install and invoke python-dotenv before instantiating the client.

Issue: Staging environment is accidentally mutating subscription data

  • Symptom: Test runs in staging are creating or modifying subscription records.
  • Likely cause: ATHLETE_NUTRITION_FEATURE_SUBSCRIPTION_MGMT is true (the default) in your staging environment.
  • Fix: Set ATHLETE_NUTRITION_FEATURE_SUBSCRIPTION_MGMT=false in your staging environment configuration. This causes all subscription management endpoints to return 403 FEATURE_DISABLED, preventing unintended billing changes.