Configuration
Environment variables, config files, feature flags
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.
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.envfile 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.
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.
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
| Variable | Required | Default | Description |
|---|---|---|---|
ATHLETE_NUTRITION_API_KEY | ✅ Yes | — | Your public API key, included as the X-API-Key header on every request. |
ATHLETE_NUTRITION_API_SECRET | ✅ Yes | — | Your client secret, used to sign request tokens. Never expose this in client-side code. |
API Connection
| Variable | Required | Default | Valid Values | Description |
|---|---|---|---|---|
ATHLETE_NUTRITION_BASE_URL | ✅ Yes | — | Any valid HTTPS URL | The root URL of the API. Use the production URL for live deployments; point to a staging URL during testing. |
ATHLETE_NUTRITION_TIMEOUT_MS | No | 10000 | Integer ≥ 1000 | Request 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_RETRIES | No | 3 | Integer 0–10 | Number of automatic retries on transient 5xx errors. Set to 0 to disable retries entirely. |
Athlete Profile & Data
| Variable | Required | Default | Valid Values | Description |
|---|---|---|---|---|
ATHLETE_NUTRITION_DEFAULT_UNITS | No | metric | metric, imperial | Default 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_LOCALE | No | en-US | BCP 47 locale tag | Controls the language and regional formatting of generated meal plan text and shopping list labels. |
Calendar Integration
| Variable | Required | Default | Valid Values | Description |
|---|---|---|---|---|
ATHLETE_NUTRITION_CALENDAR_SYNC_INTERVAL | No | 3600 | Integer (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.
| Variable | Required | Default | Valid Values | Description |
|---|---|---|---|---|
ATHLETE_NUTRITION_FEATURE_AI_ADVISOR | No | true | true, false | Enables 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_LIST | No | true | true, false | Enables the shopping list generation endpoint. Disable if your integration does not use this workflow. |
ATHLETE_NUTRITION_FEATURE_SUBSCRIPTION_MGMT | No | true | true, false | Enables subscription management endpoints. Set to false in staging environments to avoid accidental billing mutations. |
Logging & Observability
| Variable | Required | Default | Valid Values | Description |
|---|---|---|---|---|
ATHLETE_NUTRITION_LOG_LEVEL | No | warn | error, warn, info, debug | Controls 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_REQUESTS | No | false | true, false | When true, the SDK logs every outbound HTTP request URL and status code. Useful for auditing but may expose sensitive path parameters in logs. |
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.
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.
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
401with an error body like{ "error": "invalid_credentials" }. - Likely cause:
ATHLETE_NUTRITION_API_KEYis 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.envfile, and restart your process so the new value is loaded.
Issue: 403 Forbidden with error code FEATURE_DISABLED
- Symptom: A specific endpoint returns HTTP
403and the response body contains"code": "FEATURE_DISABLED". - Likely cause: The corresponding feature flag environment variable (e.g.,
ATHLETE_NUTRITION_FEATURE_AI_ADVISOR) is set tofalse. - Fix: Set the flag to
truein your.envfile 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
curlhangs and eventually exits for calls to/meal-planor/shopping-list. - Likely cause:
ATHLETE_NUTRITION_TIMEOUT_MSis set too low (default10000ms) for computationally intensive operations. - Fix: Increase the timeout. For meal plan and shopping list endpoints, a value of
30000–60000ms is recommended. SetATHLETE_NUTRITION_TIMEOUT_MS=30000in your.envfile and test again.
Issue: Unit system in responses does not match what I configured
- Symptom: Response payloads use
metricvalues even thoughATHLETE_NUTRITION_DEFAULT_UNITS=imperialis 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
unitsquery parameter in your code is overriding the default. - Fix: Ensure the variable is exported before the process starts. Search your codebase for hardcoded
unitsparameters 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
.envfile 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 invokepython-dotenvbefore 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_MGMTistrue(the default) in your staging environment. - Fix: Set
ATHLETE_NUTRITION_FEATURE_SUBSCRIPTION_MGMT=falsein your staging environment configuration. This causes all subscription management endpoints to return403 FEATURE_DISABLED, preventing unintended billing changes.