5.9 KiB
python-usda documentation
genindex
- modindex
- search
Introduction
python-usda is a fork of pygov focused on USDA's Food Composition Database API.
It was initially created to make it easier to fetch up-to-date nutritional data for some pseudo-scientific calculations in the PseudoScience project but has been extended to provide a better coverage of the API.
Warning
Since October 1, 2019, the APIs this package relies on have been deprecated. python-usda 1.x will remove those APIs and rely on the new Food Data Central APIs.
Setup
pip install python-usda
Usage
python-usda provides an API client called UsdaClient
that is the base to all API requests:
from usda import UsdaClient
= UsdaClient('API_KEY') client
The USDA API requires a Data.gov API key that you can get for free here.
Using the client, you can list food items:
= client.list_foods(5)
foods_list for _ in range(5):
= next(foods_list)
food_item print(food_item.name)
Be careful; the 5
argument in the
list_foods
method only sets the amount of items that are
returned at once; requesting one more will perform a request for another
page of 5 results.
Instead of just listing food items, it is possible to perform a text search:
= client.search_foods(
foods_search 'coffee, instant, regular, prepared with water', 1)
= next(foods_search)
coffee print(coffee)
The above code will output:
Food ID 14215 'Beverages, coffee, instant, regular, prepared with water'
We can then use this food item's ID to request a Food Report:
= client.get_food_report(coffee.id)
report for nutrient in report.nutrients:
print(nutrient.name, nutrient.value, nutrient.unit)
The above code will output:
Water 99.09 g
Energy 2.0 kcal
Protein 0.1 g
[...]
Cholesterol 0.0 mg
Caffeine 26.0 mg
And there it is, your first nutritional information report.
There is more available than mere food items and nutritional facts; head over to the API Guide to learn more.
Error handling
The API client uses requests to perform requests to USDA's API and does not explicitly handle its errors to let this library's users deal with network-related errors.
As the API has a very inconsistent way of returning errors, it cannot be fully guaranteed that all API errors are properly handled. If you encounter a case of an unhandled error response from the API, please file an issue.
All API errors are subclasses of usda.base.DataGovApiError
.
When an invalid API key is supplied, any API requests may raise a
usda.base.DataGovInvalidApiKeyError
.
When the allowed requests limit has been reached, a usda.base.DataGovApiRateExceededError
is raised.
Raw results
If you prefer to receive the raw JSON data instead of classes, append
_raw
to any client request method. For example, to retrieve
the raw JSON data for a foods list requests, use
client.list_foods_raw
. Those raw methods will pass all
keyword arguments as parameters in the request URL.
Other topics
guide contributing api