Skip to main content

USDA Food Data Central (FDC) Python Client

A comprehensive Python library for interacting with the USDA Food Data Central API, designed for easy integration with Django applications and local database caching.

Python Version License

Features

  • Complete API coverage for the USDA Food Data Central (FDC) database
  • Object-oriented interface for working with food data
  • Comprehensive data models for all FDC data types
  • Efficient caching mechanisms for Django integration
  • Support for searching, filtering, and retrieving detailed nutritional information
  • Barcode (gtin_upc) exposed on branded foods, so a barcode lookup can be verified rather than trusted
  • Request timeouts on every call, raising FdcTimeoutError instead of hanging
  • Conversion utilities for different measurement units
  • Batch operations for efficient API usage
  • Command-line interface for quick data access
  • Nutrient analysis with dietary reference intake comparisons
  • Recipe analysis with ingredient parsing and nutritional calculations
  • Visualization tools for nutrient data
  • Detailed documentation and examples

Installation

pip install usda-fdc

Or install from source:

git clone https://github.com/mcgarrah/usda_fdc_python.git
cd usda_fdc_python
pip install -e .

Quick Start

from usda_fdc import FdcClient

# Initialize the client with your API key
client = FdcClient("YOUR_API_KEY")

# Search for foods
results = client.search("apple")
for food in results.foods:
    print(f"{food.description} (FDC ID: {food.fdc_id})")

# Get detailed information for a specific food
food = client.get_food(1750340)
print(f"Food: {food.description}")
print(f"Data Type: {food.data_type}")

# Get nutrients for a food
nutrients = client.get_nutrients(1750340)
for nutrient in nutrients:
    print(f"{nutrient.name}: {nutrient.amount} {nutrient.unit_name}")

Command-Line Interface

The library includes two command-line interfaces:

FDC Client CLI

For quick access to FDC data:

# Set your API key (or use --api-key parameter)
export FDC_API_KEY=your_api_key_here

# Search for foods
fdc search "apple"

# Get detailed information for a specific food
fdc food 1750340

# Get nutrients for a food
fdc nutrients 1750340

# List foods with pagination
fdc list --page-size 5 --page-number 1

# Get help
fdc --help

Nutrient Analysis Tool (NAT)

For analyzing nutrient content and recipes:

# Analyze a food
fdc-nat analyze 1750340 --serving-size 100

# Compare multiple foods
fdc-nat compare 1750340 1750341 1750342 --nutrients vitamin_c,potassium,fiber

# Analyze a recipe
fdc-nat recipe --name "Fruit Salad" --ingredients "1 apple" "1 banana" "100g strawberries"

# Generate HTML report
fdc-nat analyze 1750340 --format html --output report.html

# Get help
fdc-nat --help

Nutrient Analysis

The library includes tools for analyzing nutrient content:

from usda_fdc import FdcClient
from usda_fdc.analysis import analyze_food, DriType, Gender

# Initialize the client
client = FdcClient("YOUR_API_KEY")

# Get a food
food = client.get_food(1750340)  # Apple, raw, with skin

# Analyze the food
analysis = analyze_food(
    food,
    dri_type=DriType.RDA,
    gender=Gender.MALE,
    serving_size=100.0
)

# Access the analysis results
print(f"Calories: {analysis.calories_per_serving} kcal")
print(f"Protein: {analysis.get_nutrient('protein').amount} g")
print(f"Vitamin C: {analysis.get_nutrient('vitamin_c').amount} mg")

Recipe Analysis

The library also supports recipe analysis:

from usda_fdc import FdcClient
from usda_fdc.analysis.recipe import create_recipe, analyze_recipe

# Initialize the client
client = FdcClient("YOUR_API_KEY")

# Create a recipe
recipe = create_recipe(
    name="Fruit Salad",
    ingredient_texts=[
        "1 apple",
        "1 banana",
        "100g strawberries"
    ],
    client=client,
    servings=2
)

# Analyze the recipe
analysis = analyze_recipe(recipe)

# Access the analysis results
per_serving = analysis.per_serving_analysis
print(f"Calories per serving: {per_serving.calories_per_serving} kcal")

Visualization

The library includes tools for visualizing nutrient data:

from usda_fdc import FdcClient
from usda_fdc.analysis import analyze_food
from usda_fdc.analysis.visualization import generate_html_report

# Initialize the client
client = FdcClient("YOUR_API_KEY")

# Get and analyze a food
food = client.get_food(1750340)
analysis = analyze_food(food)

# Generate HTML report
html = generate_html_report(analysis)
with open("report.html", "w") as f:
    f.write(html)

Django Integration

The library is designed to work seamlessly with Django applications:

from usda_fdc.django import FdcCache

# Initialize the cache with your Django models
cache = FdcCache()

# Search and cache results
results = cache.search("banana")

# Get food from cache or API
food = cache.get_food(1750340)

# Refresh cache for specific foods
cache.refresh([1750340, 1750341])

Testing

The library includes a comprehensive test suite:

# Install test dependencies
pip install -e ".[dev]"

# Run all unit tests
pytest

# Run integration tests (requires API key)
pytest -m integration

# Run Django tests (requires Django)
pytest -m django

# Run tests with coverage
pytest --cov=usda_fdc

Documentation

For detailed documentation, visit usda-fdc.readthedocs.io.

Configuration

Create a .env file in your project root with the following variables:

FDC_API_KEY=your_api_key_here
FDC_API_URL=https://api.nal.usda.gov/fdc/v1
FDC_CACHE_ENABLED=True
FDC_CACHE_TIMEOUT=86400

Examples

The library includes several example scripts in the examples directory:

  • Basic search and retrieval
  • Food details and nutrient information
  • Nutrient analysis and comparison
  • Recipe analysis
  • Django integration
  • Advanced analysis with meal planning
  • Command-line tool usage

Run the examples with:

python examples/01_basic_search.py

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Run the tests to ensure they pass (pytest)
  4. Commit your changes (git commit -m 'Add some amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • USDA Food Data Central for providing the API and data
  • Inspired by various Python USDA FDC clients

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

usda_fdc-0.2.0.tar.gz (18.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

usda_fdc-0.2.0-py3-none-any.whl (17.9 kB view details)

Uploaded Python 3

File details

Details for the file usda_fdc-0.2.0.tar.gz.

File metadata

  • Download URL: usda_fdc-0.2.0.tar.gz
  • Upload date:
  • Size: 18.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for usda_fdc-0.2.0.tar.gz
Algorithm Hash digest
SHA256 95b0cca661c2971b6312dc2ee8b3a48bc2a6b09e7beb2d09a03ad517c0ffb023
MD5 8b04065af2489ae803c84b8c77501940
BLAKE2b-256 66b1df1c2372bfc12bdc68527fd40be6edaeaac0dd02caedef9719ba8873412f

See more details on using hashes here.

File details

Details for the file usda_fdc-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: usda_fdc-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 17.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for usda_fdc-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c7f6403237e8dcf73b79a51a88478ac76de8b45aa0f0f85a055adca957e910de
MD5 a59a9cd104ec369e115631f7e4d4145a
BLAKE2b-256 fa5403d55eaefd43b29bab5d7d92f6c535d2ca80df0b420be075015d86bd6bf7

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 files

0.1.11

2 files

0.1.10

2 files

0.1.9

2 files

0.1.8

2 files

0.1.7

2 files

0.1.6

2 files

0.1.5

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page