### Setup Django integration: install, configure, migrate Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/django_integration.rst.txt Install the package with Django dependencies, add the app to INSTALLED_APPS, configure the FDC client settings, and run migrations to create the necessary database tables. ```bash pip install usda-fdc[django] ``` ```python INSTALLED_APPS = [ # ... 'usda_fdc.django', # ... ] ``` ```python # USDA FDC settings 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 # 24 hours in seconds ``` ```bash python manage.py migrate ``` -------------------------------- ### Install Documentation Dependencies from requirements-docs.txt Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/installation.html Installs documentation dependencies from the requirements-docs.txt file. ```bash pip install -r requirements-docs.txt ``` -------------------------------- ### Documentation Installation Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/installation.rst.txt Installs the package with documentation dependencies using the extras or the requirements file. ```bash pip install -e ".[docs]" ``` ```bash pip install -r requirements-docs.txt ``` -------------------------------- ### Install with Documentation Dependencies Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/installation.html Installs the package with documentation dependencies to build the documentation locally. ```bash pip install -e ".[docs]" ``` -------------------------------- ### Development Installation Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/installation.rst.txt Installs the package with development dependencies using the extras or the requirements file. ```bash pip install -e ".[dev]" ``` ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Example: get nutrients in JSON format Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Gets nutrient information in JSON format using the --format json option. ```bash fdc nutrients 1750340 --format json ``` -------------------------------- ### Install Development Dependencies from requirements-dev.txt Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/installation.html Installs development dependencies from the requirements-dev.txt file. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Install usda-fdc from source Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/index.rst.txt Clone the repository and install the package in editable mode for development. ```bash git clone https://github.com/yourusername/usda_fdc.git cd usda_fdc pip install -e . ``` -------------------------------- ### Install Django Dependencies from requirements-django.txt Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/installation.html Installs Django dependencies from the requirements-django.txt file. ```bash pip install -r requirements-django.txt ``` -------------------------------- ### Install usda-fdc with pip Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/index.rst.txt Install the usda-fdc package from PyPI using pip. ```bash pip install usda-fdc ``` -------------------------------- ### .env File Example Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/configuration.rst.txt Example contents of a .env file for the USDA FDC client. Place this file in your project root and load it with python-dotenv. ```bash 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 ``` -------------------------------- ### Install development dependencies Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/contributing.rst.txt Installs the package in editable mode along with development dependencies. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Module imports and unit registry setup Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_modules/usda_fdc/utils.html Imports required modules and initializes the Pint unit registry with common food measurement units. ```python import re from typing import Dict, Any, Optional, Tuple, Union from pint import UnitRegistry, UndefinedUnitError, DimensionalityError # Initialize unit registry ureg = UnitRegistry() # Define common food measurement units ureg.define('serving = 1 = serving') ureg.define('cup = 236.588 * milliliter = cup') ureg.define('tablespoon = 14.7868 * milliliter = tbsp') ureg.define('teaspoon = 4.92892 * milliliter = tsp') ureg.define('ounce = 28.3495 * gram = oz') ureg.define('pound = 453.592 * gram = lb') ureg.define('slice = 1 = slice') ureg.define('piece = 1 = piece') ``` -------------------------------- ### Example: search for apple Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Searches for foods containing 'apple'. ```bash fdc search "apple" ``` -------------------------------- ### Command-line interface usage Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/quickstart.rst.txt Shows common fdc CLI commands for searching foods, getting food details, getting nutrients, and listing foods. ```bash # Search for foods fdc search "apple" --page-size 5 # Get food details fdc food 1750340 # Get nutrients for a food fdc nutrients 1750340 # List foods fdc list --page-size 10 --page-number 1 ``` -------------------------------- ### Django Integration Installation Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/installation.rst.txt Installs the package with Django dependencies using the extras or the requirements file. ```bash pip install -e ".[django]" ``` ```bash pip install -r requirements-django.txt ``` -------------------------------- ### Install usda-fdc with Django dependencies Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/django_integration.html Installs the USDA FDC library with Django integration dependencies. ```bash pip install usda-fdc[django] ``` -------------------------------- ### Example: list branded foods Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Lists only branded foods using the --data-type option. ```bash fdc list --data-type "Branded" ``` -------------------------------- ### Example tests for FdcClient Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/testing.rst.txt Example pytest tests for the FdcClient class, covering a successful search and an API error case. Uses a fixture to create a client with a test API key and mocks the _make_request method. ```python import pytest from unittest.mock import patch, MagicMock from usda_fdc import FdcClient, FdcApiError @pytest.fixture def client(): return FdcClient(api_key="test_key") def test_search_success(client): # Mock the API response mock_response = { "totalHits": 1, "currentPage": 1, "totalPages": 1, "foods": [ { "fdcId": 1234, "description": "Test Food", "dataType": "Branded" } ] } with patch.object(client, "_make_request", return_value=mock_response): result = client.search("test") assert result.total_hits == 1 assert len(result.foods) == 1 assert result.foods[0].fdc_id == 1234 assert result.foods[0].description == "Test Food" def test_search_api_error(client): with patch.object(client, "_make_request", side_effect=FdcApiError("API error")): with pytest.raises(FdcApiError): client.search("test") ``` -------------------------------- ### fdc search command example Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/cli.html Searches for foods using keywords, with options to control page size and page number. ```bash fdc search "apple" --page-size 10 --page-number 1 ``` -------------------------------- ### Basic Error Handling with FdcClient Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/error_handling.html Basic error handling example showing how to catch specific exceptions like FdcAuthError and FdcRateLimitError, with a fallback for generic FdcApiError and Exception. ```python from usda_fdc import FdcClient, FdcApiError, FdcAuthError, FdcRateLimitError client = FdcClient(api_key="your_api_key_here") try: food = client.get_food(1750340) except FdcAuthError: print("Authentication failed. Check your API key.") except FdcRateLimitError: print("Rate limit exceeded. Try again later.") except FdcApiError as e: print(f"API error: {e}") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Rate Limiting with RateLimitedClient Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/advanced_usage.html Implement a rate-limited client by overriding `_make_request` to enforce a maximum number of requests per minute. The example sets `requests_per_minute=5` and uses `time.sleep` to wait between requests. ```python import time from usda_fdc import FdcClient class RateLimitedClient(FdcClient): def __init__(self, api_key, requests_per_minute=10, **kwargs): super().__init__(api_key, **kwargs) self.requests_per_minute = requests_per_minute self.interval = 60 / requests_per_minute self.last_request_time = 0 def _make_request(self, endpoint, method="GET", params=None, data=None): # Wait if needed current_time = time.time() time_since_last = current_time - self.last_request_time if time_since_last < self.interval: time.sleep(self.interval - time_since_last) # Make the request result = super()._make_request(endpoint, method, params, data) # Update last request time self.last_request_time = time.time() return result # Use the rate-limited client client = RateLimitedClient( api_key="your_api_key_here", requests_per_minute=5 # Maximum 5 requests per minute ) ``` -------------------------------- ### Mock _make_request with unittest.mock Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/testing.rst.txt Example unit test for the _make_request method using unittest.mock to patch requests.Session.request. Verifies the method returns the JSON response and that the request is called once. ```python from unittest.mock import patch, MagicMock @patch("requests.Session.request") def test_make_request(mock_request, client): mock_response = MagicMock() mock_response.status_code = 200 mock_response.json.return_value = {"key": "value"} mock_request.return_value = mock_response result = client._make_request("endpoint") assert result == {"key": "value"} mock_request.assert_called_once() ``` -------------------------------- ### Custom API request with _make_request Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/advanced_usage.rst.txt Use the low-level _make_request method for custom API requests. Requires an API key. The example shows a search for 'apple' with pagination and sorting parameters. ```python from usda_fdc import FdcClient client = FdcClient(api_key="your_api_key_here") # Make a custom request data = client._make_request( endpoint="foods/search", params={ "query": "apple", "pageSize": 25, "pageNumber": 1, "sortBy": "dataType.keyword", "sortOrder": "asc" } ) ``` -------------------------------- ### fdc nutrients command Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Gets nutrient information for a specific food by its FDC ID. ```bash fdc nutrients 1750340 ``` -------------------------------- ### Unit conversion with convert_measurement and parse_unit_and_value Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/advanced_usage.rst.txt Convert between measurement units and parse measurement strings. The example converts 1 cup to grams, parses '2.5 tbsp', and converts 1 oz to grams. ```python from usda_fdc.utils import convert_measurement, parse_unit_and_value # Convert between units grams = convert_measurement(1, "cup", "g") print(f"1 cup = {grams} grams") # Parse a measurement string amount, unit = parse_unit_and_value("2.5 tbsp") print(f"Amount: {amount}, Unit: {unit}") # Convert to grams from usda_fdc.utils import convert_to_grams grams = convert_to_grams(1, "oz") print(f"1 oz = {grams} grams") ``` -------------------------------- ### Cache popular foods with background tasks using async_task Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/django_integration.rst.txt Define a function to cache popular foods and schedule it as a background task using Django Q's async_task. The example shows integration with task queues like Celery or Django Q. ```python from usda_fdc.django import FdcCache def cache_popular_foods(): cache = FdcCache() popular_ids = [1750340, 1750341, 1750342] # Example IDs cache.get_foods(popular_ids) # Use with Celery, Django Q, or other task queues from django_q.tasks import async_task async_task(cache_popular_foods) ``` -------------------------------- ### Set up pre-commit hooks Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/contributing.rst.txt Sets up pre-commit hooks for the repository. ```bash pre-commit install ``` -------------------------------- ### Use .env file for API key Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Shows how to use a .env file to set the API key and then run a search. ```bash # .env file FDC_API_KEY=your_api_key_here # Then run fdc search "apple" ``` -------------------------------- ### Build documentation locally Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/contributing.rst.txt Builds the documentation locally using Sphinx's make html command and opens the generated HTML in a browser. ```bash cd docs make html # Open _build/html/index.html in your browser ``` -------------------------------- ### FdcClient.__init__() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/api/cli.html Initializes the FDC client with an API key and optional base URL. Sets up the session for making HTTP requests. ```APIDOC ## FdcClient.__init__() ### Description Initializes the FDC client with an API key and optional base URL. Sets up the session for making HTTP requests. ### Method Constructor ### Signature `FdcClient(api_key: str, base_url: str = None)` ### Parameters - **api_key** (str) - Required - The API key for authenticating with the USDA FDC API. - **base_url** (str) - Optional - The base URL for the FDC API. Defaults to the official API endpoint. ### Attributes - **api_key** (str) - The API key used for authentication. - **base_url** (str) - The base URL for API requests. - **session** (requests.Session) - The HTTP session used for making requests. ``` -------------------------------- ### Food.__init__(fdc_id, description, data_type, publication_date=None, food_class=None, food_category=None, scientific_name=None, brand_owner=None, brand_name=None, ingredients=None, serving_size=None, serving_size_unit=None, household_serving_fulltext=None, nutrients=, food_portions=) Source: https://usda-fdc.readthedocs.io/en/v0.1.1/api/models.html Constructor for the Food class. Initializes a Food object with all its attributes, including optional fields and lists of nutrients and food portions. ```APIDOC ## Food.__init__(fdc_id, description, data_type, publication_date=None, food_class=None, food_category=None, scientific_name=None, brand_owner=None, brand_name=None, ingredients=None, serving_size=None, serving_size_unit=None, household_serving_fulltext=None, nutrients=, food_portions=) ### Description Initializes a Food instance. ### Parameters - **fdc_id** (int) - Required - Food Data Central ID. - **description** (str) - Required - Description of the food. - **data_type** (str) - Required - Type of data (e.g., 'branded', 'survey'). - **publication_date** (str | None) - Optional - Publication date. - **food_class** (str | None) - Optional - Food class. - **food_category** (str | None) - Optional - Food category. - **scientific_name** (str | None) - Optional - Scientific name. - **brand_owner** (str | None) - Optional - Brand owner. - **brand_name** (str | None) - Optional - Brand name. - **ingredients** (str | None) - Optional - Ingredients list. - **serving_size** (float | None) - Optional - Serving size. - **serving_size_unit** (str | None) - Optional - Unit of serving size. - **household_serving_fulltext** (str | None) - Optional - Household serving full text. - **nutrients** (List[Nutrient]) - Optional - List of nutrients. - **food_portions** (List[FoodPortion]) - Optional - List of food portions. ### Returns - None ``` -------------------------------- ### main() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/api/cli.html Main entry point for the command-line interface. Parses arguments and dispatches to subcommands. ```APIDOC ## main() ### Description Main entry point for the command-line interface. Parses arguments and dispatches to subcommands. ### Method main ### Signature `main(argv: List[str] = None)` ### Parameters - **argv** (List[str]) - Optional - Command-line arguments. Defaults to sys.argv[1:]. ### Returns - **int** - Exit code. ``` -------------------------------- ### list_foods Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_modules/usda_fdc/client.html Get a paged list of foods. ```APIDOC ## list_foods(data_type=None, page_size=50, page_number=1, sort_by=None, sort_order=None) ### Description Get a paged list of foods. ### Method list_foods ### Parameters - **data_type** (Optional[List[str]]) - Optional - Filter on specific data types. - **page_size** (int) - Optional - Maximum number of results to return (1-200). Default: 50. - **page_number** (int) - Optional - Page number to retrieve. Default: 1. - **sort_by** (Optional[str]) - Optional - Field to sort by. - **sort_order** (Optional[str]) - Optional - Sort direction ("asc" or "desc"). ### Returns A list of Food objects. ``` -------------------------------- ### get_foods Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_modules/usda_fdc/client.html Get detailed information for multiple foods by FDC ID. ```APIDOC ## get_foods(fdc_ids, format="full", nutrients=None) ### Description Get detailed information for multiple foods by FDC ID. ### Method get_foods ### Parameters - **fdc_ids** (List[Union[str, int]]) - Required - List of FDC IDs (max 20). - **format** (str) - Optional - The format of the response ("full" or "abridged"). Default: "full". - **nutrients** (Optional[List[int]]) - Optional - List of up to 25 nutrient numbers to include. ### Returns A list of Food objects. ``` -------------------------------- ### SearchResultFood.__init__() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/api/cli.html Initializes a SearchResultFood object with its attributes. ```APIDOC ## SearchResultFood.__init__() ### Description Initializes a SearchResultFood object with its attributes. ### Method Constructor ### Signature `SearchResultFood(fdc_id: int, description: str, data_type: str, publication_date: str = None, food_category: str = None, brand_owner: str = None, brand_name: str = None)` ### Parameters - **fdc_id** (int) - Required - The FDC ID. - **description** (str) - Required - The food description. - **data_type** (str) - Required - The data type. - **publication_date** (str) - Optional - The publication date. - **food_category** (str) - Optional - The food category. - **brand_owner** (str) - Optional - The brand owner. - **brand_name** (str) - Optional - The brand name. ``` -------------------------------- ### fdc nutrients FOOD_ID Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Get nutrient information for a specific food by its FDC ID. ```APIDOC ## fdc nutrients FOOD_ID ### Description Get nutrient information for a specific food. ### Method CLI ### Endpoint fdc nutrients ### Parameters #### Arguments - **FOOD_ID** (integer) - Required - FDC ID of the food (e.g., 1750340) ### Request Example ```bash fdc nutrients 1750340 --format json ``` ### Response #### Success Response Nutrient information in the specified format. ``` -------------------------------- ### Global options for fdc Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Lists global options that apply to all fdc commands: --api-key, --format, --version, --help. ```bash --api-key KEY FDC API key (can also be set via FDC_API_KEY environment variable) --format FORMAT Output format: json, pretty, or text (default: pretty) --version Show version and exit --help Show help message and exit ``` -------------------------------- ### fdc food FOOD_ID Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Get detailed information about a specific food by its FDC ID. ```APIDOC ## fdc food FOOD_ID ### Description Get detailed information about a specific food. ### Method CLI ### Endpoint fdc food ### Parameters #### Arguments - **FOOD_ID** (integer) - Required - FDC ID of the food (e.g., 1750340) ### Request Example ```bash fdc food 1750340 ``` ### Response #### Success Response Detailed food information in the specified format. ``` -------------------------------- ### fdc food command Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Gets detailed information about a specific food by its FDC ID. ```bash fdc food 1750340 ``` -------------------------------- ### Food.__init__() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/api/cli.html Initializes a Food object with its attributes. Typically not called directly; use from_api_data instead. ```APIDOC ## Food.__init__() ### Description Initializes a Food object with its attributes. Typically not called directly; use from_api_data instead. ### Method Constructor ### Signature `Food(fdc_id: int, description: str, data_type: str, publication_date: str = None, food_class: str = None, food_category: str = None, scientific_name: str = None, brand_owner: str = None, brand_name: str = None, ingredients: str = None, serving_size: float = None, serving_size_unit: str = None, household_serving_fulltext: str = None, nutrients: List[Nutrient] = None, food_portions: List[FoodPortion] = None)` ### Parameters - **fdc_id** (int) - Required - The unique FDC ID. - **description** (str) - Required - The food description. - **data_type** (str) - Required - The data type (e.g., 'Foundation'). - **publication_date** (str) - Optional - The publication date. - **food_class** (str) - Optional - The food class. - **food_category** (str) - Optional - The food category. - **scientific_name** (str) - Optional - The scientific name. - **brand_owner** (str) - Optional - The brand owner. - **brand_name** (str) - Optional - The brand name. - **ingredients** (str) - Optional - The ingredients. - **serving_size** (float) - Optional - The serving size. - **serving_size_unit** (str) - Optional - The unit of serving size. - **household_serving_fulltext** (str) - Optional - Household serving full text. - **nutrients** (List[Nutrient]) - Optional - List of nutrients. - **food_portions** (List[FoodPortion]) - Optional - List of food portions. ``` -------------------------------- ### Set API key via environment variable Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Shows how to set the FDC_API_KEY environment variable and then run a search. ```bash export FDC_API_KEY=your_api_key_here fdc search "apple" ``` -------------------------------- ### Filter foods by data type Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/quickstart.rst.txt Filters foods by data type using the data_type parameter. Shows examples for 'Branded' and for 'Foundation' and 'SR Legacy'. ```python # Get only branded foods branded_foods = client.list_foods(data_type=["Branded"]) # Get foundation and SR Legacy foods foundation_foods = client.list_foods(data_type=["Foundation", "SR Legacy"]) ``` -------------------------------- ### Get multiple foods by FDC IDs Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/quickstart.rst.txt Retrieves information for multiple foods at once using a list of FDC IDs and prints each food's description and data type. ```python # Get multiple foods by FDC ID foods = client.get_foods([1750340, 1750341, 1750342]) # Process foods for food in foods: print(f"{food.description} ({food.data_type})") ``` -------------------------------- ### Import and initialize FdcClient with API key Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/quickstart.rst.txt Loads the API key from a .env file using python-dotenv and initializes the FdcClient. Requires the FDC_API_KEY environment variable to be set. ```python from usda_fdc import FdcClient import os from dotenv import load_dotenv # Load API key from .env file load_dotenv() api_key = os.getenv("FDC_API_KEY") # Initialize client client = FdcClient(api_key) ``` -------------------------------- ### FoodPortion.__init__() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/api/cli.html Initializes a FoodPortion object with its attributes. ```APIDOC ## FoodPortion.__init__() ### Description Initializes a FoodPortion object with its attributes. ### Method Constructor ### Signature `FoodPortion(id: int, amount: float, gram_weight: float, portion_description: str = None, modifier: str = None, measure_unit: str = None)` ### Parameters - **id** (int) - Required - The portion ID. - **amount** (float) - Required - The amount. - **gram_weight** (float) - Required - The gram weight. - **portion_description** (str) - Optional - The portion description. - **modifier** (str) - Optional - The modifier. - **measure_unit** (str) - Optional - The measure unit. ``` -------------------------------- ### Client Initialization with API Key and Custom URL Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/configuration.rst.txt Initialize the FdcClient with an API key and optionally a custom base URL. The base_url overrides the default API endpoint. ```python from usda_fdc import FdcClient # Basic initialization with API key client = FdcClient(api_key="your_api_key_here") # Custom API URL client = FdcClient( api_key="your_api_key_here", base_url="https://custom-api-url.example.com" ) ``` -------------------------------- ### Get food details by FDC ID Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/quickstart.rst.txt Retrieves detailed information for a specific food using its FDC ID, including description, data type, brand name, and nutrient amounts. ```python # Get food by FDC ID food = client.get_food(1750340) # Print food details print(f"Food: {food.description}") print(f"Data Type: {food.data_type}") print(f"Brand: {food.brand_name}") # Print nutrients print("\nNutrients:") for nutrient in food.nutrients: print(f"{nutrient.name}: {nutrient.amount} {nutrient.unit_name}") ``` -------------------------------- ### Initialize FdcClient with API key and base URL Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_modules/usda_fdc/client.html Initializes the FDC client with an optional API key and base URL. If no API key is provided, it falls back to the FDC_API_KEY environment variable; if neither is available, a ValueError is raised. The default base URL is https://api.nal.usda.gov/fdc/v1/. ```python class FdcClient: """ Client for interacting with the USDA Food Data Central API. Attributes: api_key (str): The API key for authenticating with the FDC API. base_url (str): The base URL for the FDC API. session (requests.Session): A session object for making HTTP requests. """ def __init__( self, api_key: Optional[str] = None, base_url: str = "https://api.nal.usda.gov/fdc/v1/" ): """ Initialize the FDC client. Args: api_key: The API key for authenticating with the FDC API. If not provided, will look for FDC_API_KEY environment variable. base_url: The base URL for the FDC API. Raises: ValueError: If no API key is provided or found in environment variables. """ self.api_key = api_key or os.environ.get("FDC_API_KEY") if not self.api_key: raise ValueError( "No API key provided. Pass api_key parameter or set FDC_API_KEY environment variable." ) self.base_url = base_url self.session = requests.Session() ``` -------------------------------- ### FdcClient.__init__() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/dev/contributing.html Initializes a new FdcClient instance with the provided API key and base URL. This constructor sets up the client for making requests to the USDA Food Data Central API. ```APIDOC ## FdcClient.__init__() ### Description Initializes a new FdcClient instance with the provided API key and base URL. This constructor sets up the client for making requests to the USDA Food Data Central API. ### Method Constructor ### Signature `FdcClient(api_key: str, base_url: str = "https://api.nal.usda.gov/fdc/v1")` ### Parameters - **api_key** (str) - Required - The API key for authenticating with the USDA FDC API. - **base_url** (str) - Optional - The base URL for the FDC API. Defaults to `https://api.nal.usda.gov/fdc/v1`. ### Attributes - **api_key** (str) - The API key used for authentication. - **base_url** (str) - The base URL for the API. - **session** (requests.Session) - The HTTP session used for making requests. ``` -------------------------------- ### Nutrient.__init__() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/api/cli.html Initializes a Nutrient object with its attributes. ```APIDOC ## Nutrient.__init__() ### Description Initializes a Nutrient object with its attributes. ### Method Constructor ### Signature `Nutrient(id: int, name: str, amount: float, unit_name: str, nutrient_nbr: int = None, rank: int = None)` ### Parameters - **id** (int) - Required - The nutrient ID. - **name** (str) - Required - The nutrient name. - **amount** (float) - Required - The amount of the nutrient. - **unit_name** (str) - Required - The unit name (e.g., 'g', 'mg'). - **nutrient_nbr** (int) - Optional - The nutrient number. - **rank** (int) - Optional - The rank. ``` -------------------------------- ### Clone the repository Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/contributing.rst.txt Clones the forked repository and navigates into the project directory. ```bash git clone https://github.com/yourusername/usda_fdc.git cd usda_fdc ``` -------------------------------- ### Use FdcCache to search and get foods with caching Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/django_integration.rst.txt Use FdcCache to search and retrieve food data with automatic caching in Django models and cache. The force_refresh=True parameter bypasses the cache and fetches from the API. ```python from usda_fdc.django import FdcCache # Initialize the cache cache = FdcCache() # Search for foods (results will be cached) results = cache.search("apple") # Get a food by FDC ID (will be cached in database) food = cache.get_food(1750340) # Get multiple foods (will use database cache when available) foods = cache.get_foods([1750340, 1750341, 1750342]) # Force refresh from API food = cache.get_food(1750340, force_refresh=True) ``` -------------------------------- ### fdc list command with options Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Lists foods with pagination, with options for data type, page size, and page number. ```bash fdc list --page-size 10 --page-number 1 ``` ```bash --data-type TYPE Filter by data type (can be specified multiple times) --page-size SIZE Results per page (default: 10) --page-number NUM Page number (default: 1) ``` -------------------------------- ### Upload to PyPI Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/releasing.rst.txt Upload the built distribution packages to PyPI. ```bash python -m twine upload dist/* ``` -------------------------------- ### Extend Food model with custom methods Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/advanced_usage.rst.txt Extend the Food model to add custom calculations. The EnhancedFood class adds methods to calculate calories per gram and protein percentage. Requires an API key and a valid food ID (example uses 1750340). ```python from usda_fdc import FdcClient from usda_fdc.models import Food class EnhancedFood(Food): def calculate_calories_per_gram(self): for nutrient in self.nutrients: if nutrient.name == "Energy" and nutrient.unit_name == "kcal": return nutrient.amount / 100 # per gram return 0 def calculate_protein_percentage(self): energy = 0 protein_energy = 0 for nutrient in self.nutrients: if nutrient.name == "Energy" and nutrient.unit_name == "kcal": energy = nutrient.amount elif nutrient.name == "Protein" and nutrient.unit_name == "g": # Protein has 4 calories per gram protein_energy = nutrient.amount * 4 if energy > 0: return (protein_energy / energy) * 100 return 0 # Use the enhanced class client = FdcClient(api_key="your_api_key_here") food_data = client.get_food(1750340) # Convert to enhanced food enhanced_food = EnhancedFood( fdc_id=food_data.fdc_id, description=food_data.description, data_type=food_data.data_type, nutrients=food_data.nutrients, food_portions=food_data.food_portions ) print(f"Calories per gram: {enhanced_food.calculate_calories_per_gram()}") print(f"Protein percentage: {enhanced_food.calculate_protein_percentage()}%") ``` -------------------------------- ### Query food data with Django ORM using FoodModel and NutrientModel Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/django_integration.rst.txt Query food data directly using Django's ORM with FoodModel and NutrientModel. The example filters branded foods and retrieves foods with protein amount greater than 20, using select_related to optimize queries. ```python from usda_fdc.django.models import FoodModel, NutrientModel # Query foods directly using Django's ORM branded_foods = FoodModel.objects.filter(data_type="Branded") # Get foods with specific nutrients high_protein = NutrientModel.objects.filter( name="Protein", amount__gt=20 ).select_related('food') for nutrient in high_protein: print(f"{nutrient.food.description}: {nutrient.amount}g protein") ``` -------------------------------- ### Set next development version Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/releasing.rst.txt Set the next development version in usda_fdc/__init__.py after releasing. ```python __version__ = "X.Y+1.0.dev0" ``` -------------------------------- ### CLI Configuration with Environment Variable and Argument Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/configuration.rst.txt Configure the CLI using an environment variable or a command-line argument. Set FDC_API_KEY or pass --api-key to the fdc command. ```bash # Set environment variable export FDC_API_KEY=your_api_key_here # Use the CLI fdc search "apple" # Or provide the API key as an argument fdc --api-key your_api_key_here search "apple" ``` -------------------------------- ### Create git tag Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/releasing.rst.txt Create an annotated git tag for the release version. ```bash git tag -a vX.Y.Z -m "Version X.Y.Z" ``` -------------------------------- ### Build distribution packages Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/releasing.rst.txt Build distribution packages. Creates both a source distribution and a wheel in the dist/ directory. ```bash python -m build ``` -------------------------------- ### Update version in usda_fdc/__init__.py Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/releasing.rst.txt Set the version number in usda_fdc/__init__.py before releasing. Replace X.Y.Z with the actual version. ```python __version__ = "X.Y.Z" ``` -------------------------------- ### Run pre-commit on all files Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/contributing.rst.txt Runs all pre-commit hooks on all files to automatically apply formatting and linting checks. ```bash pre-commit run --all-files ``` -------------------------------- ### list_command() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/api/cli.html Handles the 'list' CLI command. Lists foods with optional filtering. ```APIDOC ## list_command() ### Description Handles the 'list' CLI command. Lists foods with optional filtering. ### Method list_command ### Signature `list_command(args)` ### Parameters - **args** (Namespace) - Required - Parsed command-line arguments. ### Returns - **int** - Exit code. ``` -------------------------------- ### Create release commit Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/releasing.rst.txt Commit the version and changelog changes for the release. ```bash git add usda_fdc/__init__.py CHANGELOG.md git commit -m "Release vX.Y.Z" ``` -------------------------------- ### fdc command syntax Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Shows the general syntax for the fdc CLI: fdc [options] [command-options]. ```bash fdc [options] [command-options] ``` -------------------------------- ### Mock requests.Session.request with unittest.mock Source: https://usda-fdc.readthedocs.io/en/v0.1.1/dev/testing.html Shows how to mock the requests.Session.request method using unittest.mock for unit tests. ```python from unittest.mock import patch, MagicMock @patch("requests.Session.request") def test_make_request(mock_request, client): mock_response = MagicMock() mock_response.status_code = 200 mock_response.json.return_value = {"key": "value"} mock_request.return_value = mock_response result = client._make_request("endpoint") assert result == {"key": "value"} mock_request.assert_called_once() ``` -------------------------------- ### usda_fdc.cli source: list_command and main Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_modules/usda_fdc/cli.html The source code for the usda_fdc.cli module includes two functions: list_command and main. list_command handles the 'list' subcommand, using FdcClient to fetch foods and printing them with format_output, exiting on FdcApiError. main sets up the argparse CLI with subcommands search, food, nutrients, and list, loads environment variables, and requires an API key from --api-key or FDC_API_KEY. ```python def list_command(args: argparse.Namespace) -> None: """Handle list command.""" client = FdcClient(args.api_key) try: foods = client.list_foods( data_type=args.data_type, page_size=args.page_size, page_number=args.page_number ) print(f"Listing {len(foods)} foods (page {args.page_number}):") for food in foods: print(format_output(food, args.format)) if args.format != "json": print("-" * 40) except FdcApiError as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) ``` ```python def main() -> None: """Main entry point for the CLI.""" # Load environment variables from .env file load_dotenv() # Create the top-level parser parser = argparse.ArgumentParser( prog="fdc", description="USDA Food Data Central (FDC) command-line interface" ) parser.add_argument( "--version", action="version", version=f"%(prog)s {__version__}" ) parser.add_argument( "--api-key", default=os.environ.get("FDC_API_KEY"), help="FDC API key (can also be set via FDC_API_KEY environment variable)" ) parser.add_argument( "--format", choices=["json", "pretty", "text"], default="pretty", help="Output format (default: pretty)" ) # Create subparsers for commands subparsers = parser.add_subparsers(dest="command", help="Command to execute") # Search command search_parser = subparsers.add_parser("search", help="Search for foods") search_parser.add_argument("query", help="Search query") search_parser.add_argument("--data-type", nargs="+", help="Filter by data type") search_parser.add_argument("--page-size", type=int, default=10, help="Results per page") search_parser.add_argument("--page-number", type=int, default=1, help="Page number") search_parser.set_defaults(func=search_command) # Food command food_parser = subparsers.add_parser("food", help="Get food details") food_parser.add_argument("fdc_id", help="FDC ID of the food") food_parser.set_defaults(func=food_command) # Nutrients command nutrients_parser = subparsers.add_parser("nutrients", help="Get food nutrients") nutrients_parser.add_argument("fdc_id", help="FDC ID of the food") nutrients_parser.set_defaults(func=nutrients_command) # List command list_parser = subparsers.add_parser("list", help="List foods") list_parser.add_argument("--data-type", nargs="+", help="Filter by data type") list_parser.add_argument("--page-size", type=int, default=10, help="Results per page") list_parser.add_argument("--page-number", type=int, default=1, help="Page number") list_parser.set_defaults(func=list_command) # Parse arguments args = parser.parse_args() # Check if API key is provided if not args.api_key: print("Error: No API key provided. Use --api-key or set FDC_API_KEY environment variable.", file=sys.stderr) sys.exit(1) # Execute command if provided if hasattr(args, "func"): args.func(args) else: parser.print_help() if __name__ == "__main__": main() ``` -------------------------------- ### list_command() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_modules/usda_fdc/client.html Handles the 'list' CLI command. ```APIDOC ## list_command() ### Description Executes the list command, listing foods with optional filters. ### Method list_command ### Signature `list_command(args: argparse.Namespace) -> None` ### Parameters - **args** (argparse.Namespace) - Required - Parsed command-line arguments. ### Returns - **None** - This function does not return a value. ``` -------------------------------- ### Run integration tests with API key Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/testing.rst.txt Sets the FDC_API_KEY environment variable and runs integration tests. Requires a valid API key. ```bash # Set API key for integration tests export FDC_API_KEY=your_api_key_here # Run integration tests pytest tests/integration/ ``` -------------------------------- ### Run Django migrations for FDC Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/django_integration.html Runs Django migrations to create the necessary database tables for the FDC cache. ```bash python manage.py migrate ``` -------------------------------- ### SearchResult.__init__() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/api/cli.html Initializes a SearchResult object with its attributes. ```APIDOC ## SearchResult.__init__() ### Description Initializes a SearchResult object with its attributes. ### Method Constructor ### Signature `SearchResult(foods: List[SearchResultFood], total_hits: int, current_page: int, total_pages: int)` ### Parameters - **foods** (List[SearchResultFood]) - Required - The list of food results. - **total_hits** (int) - Required - The total number of hits. - **current_page** (int) - Required - The current page number. - **total_pages** (int) - Required - The total number of pages. ``` -------------------------------- ### List foods with pagination Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/quickstart.rst.txt Lists foods with pagination using page_size and page_number parameters, and shows how to retrieve the next page. ```python # List foods with pagination foods = client.list_foods(page_size=10, page_number=1) # Process foods for food in foods: print(f"{food.description} (FDC ID: {food.fdc_id})") # Get next page next_page = client.list_foods(page_size=10, page_number=2) ``` -------------------------------- ### Cache food data with background tasks Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/django_integration.html Shows how to cache large datasets using background tasks with Django Q or other task queues. ```python from usda_fdc.django import FdcCache def cache_popular_foods(): cache = FdcCache() popular_ids = [1750340, 1750341, 1750342] # Example IDs cache.get_foods(popular_ids) # Use with Celery, Django Q, or other task queues from django_q.tasks import async_task async_task(cache_popular_foods) ``` -------------------------------- ### Run integration-marked tests Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/testing.rst.txt Runs tests marked with the integration marker. These tests are skipped by default. ```bash pytest -m integration ``` -------------------------------- ### Push commit and tag to GitHub Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/releasing.rst.txt Push the release commit and tag to GitHub. ```bash git push origin main git push origin vX.Y.Z ``` -------------------------------- ### list_foods() Source: https://usda-fdc.readthedocs.io/en/v0.1.1/genindex.html Lists all available food items. ```APIDOC ## list_foods() ### Description Lists all available food items. ### Method GET ### Endpoint `/foods` ### Parameters #### Query Parameters - **page** (integer) - Optional - Page number for pagination. - **page_size** (integer) - Optional - Number of results per page. ### Response #### Success Response (200) - **foods** (array) - List of food items. #### Response Example ```json { "foods": [ { "id": "12345", "description": "Example food" } ] } ``` ``` -------------------------------- ### Add usda_fdc.django to INSTALLED_APPS Source: https://usda-fdc.readthedocs.io/en/v0.1.1/user/django_integration.html Adds the usda_fdc.django app to Django's INSTALLED_APPS in settings.py. ```python INSTALLED_APPS = [ # ... 'usda_fdc.django', # ... ] ``` -------------------------------- ### fdc search command with options Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/user/cli.rst.txt Searches for foods using keywords, with options for data type, page size, and page number. ```bash fdc search "apple" --page-size 10 --page-number 1 ``` ```bash --data-type TYPE Filter by data type (can be specified multiple times) --page-size SIZE Results per page (default: 10) --page-number NUM Page number (default: 1) ``` -------------------------------- ### Run code style tools manually Source: https://usda-fdc.readthedocs.io/en/v0.1.1/dev/contributing.html Runs Black, isort, flake8, and mypy manually on the source and test directories. ```bash # Format code black usda_fdc tests # Sort imports isort usda_fdc tests # Lint code flake8 usda_fdc tests # Type check mypy usda_fdc ``` -------------------------------- ### Run tests with pytest Source: https://usda-fdc.readthedocs.io/en/v0.1.1/dev/testing.html Runs the test suite for the USDA FDC Python Client using pytest. ```bash pytest ``` -------------------------------- ### Run tests with coverage Source: https://usda-fdc.readthedocs.io/en/v0.1.1/_sources/dev/testing.rst.txt Runs tests with coverage for the usda_fdc package. ```bash pytest --cov=usda_fdc ```