Open yuh2k opened 4 months ago
Apply for a new key, and make use of the API like below
Request info for banana: https://api.nal.usda.gov/fdc/v1/foods/search?api_key=9qFCblx5eGXl0YaaVf8tunrl8qFLjbwoXSl4eWXa&query=banana
And follow this doc: https://fdc.nal.usda.gov/api-guide.html
here is an example React component for seaching for a food
The page prompts the user to put a food name as a query
import React, { useState } from 'react'; import axios from 'axios';
function FoodSearch() { const [query, setQuery] = useState(''); const [results, setResults] = useState([]);
const handleSubmit = async (event) => {
event.preventDefault();
const apiUrl = 'https://api.nal.usda.gov/fdc/v1/foods/search';
const apiKey = 'IMPORT YOUR KEY HERE';
// Modify your request json here, hardcoding is not a good practice but I put some example here for better viewing
const body = {
query: query,
dataType: ["Foundation", "SR Legacy"],
pageSize: 25,
pageNumber: 2,
sortBy: "dataType.keyword",
sortOrder: "asc",
startDate: "2021-01-01",
endDate: "2021-12-30"
};
try {
const response = await axios.post(apiUrl + '?api_key=' + apiKey, body);
setResults(response.data.foods);
} catch (error) {
console.error('Error fetching food data:', error);
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Enter a food item (e.g., Cheddar cheese)"
/>
<button type="submit">Search</button>
</form>
<div>
{results.length > 0 && (
<ul>
{results.map((food, index) => (
<li key={index}>
<strong>{food.description}</strong>
<p>Nutrients:</p>
<ul>
{food.foodNutrients.map((nutrient, index) => (
<li key={index}>{nutrient.nutrientName}: {nutrient.value}{nutrient.unitName}</li>
))}
</ul>
</li>
))}
</ul>
)}
</div>
</div>
);
}
export default FoodSearch;
Details of food search API: https://app.swaggerhub.com/apis/fdcnal/food-data_central_api/1.0.1#/FDC/getFoodsSearch
https://docs.google.com/document/d/1Zlvlez4wMpszWyEWul8FJqewKsUHBgaJFJkESYMyWQg/edit#heading=h.4lowupgq0n03