Last active
January 11, 2017 20:03
-
-
Save PrateekKumarSingh/d418f520fe6bb102538f23691d9d3135 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Get-Nutrient | |
{ | |
[cmdletbinding()] | |
[Alias("Nutrient")] | |
Param | |
( | |
[Parameter(Mandatory=$True)] [String] $Query | |
) | |
$Script:i=0 | |
Write-Verbose "Searching `"$Query`" in Nutrient database.." | |
# Send Web request to the REST API to Search items with the user given Query/Item | |
$result = (Invoke-RestMethod -Uri "http://api.nal.usda.gov/ndb/search/?format=json&q=$Query&sort=n&offset=0&api_key=YOURSUBSCRIPTIONKEYGOESHERE").list.item |` | |
select @{n='Choice';e={$Script:i=$Script:i+1;$Script:i}},` | |
@{n='Name';e={(Get-Culture).textinfo.totitlecase(($_.name -split ", UPC: ")[0].ToLower())}},` | |
@{n='Category';e={$_.Group}},@{n='12DigitBarCode';e={$barcode=($_.name -split "UPC: ")[1];If($barcode){$barcode}else{"NA"}}}, | |
@{n='NutrientDBNo';e={$_.Ndbno}} | |
# Display results from the Search and Get the Choice from the user | |
If($result) | |
{ | |
Write-host "$($result |select Choice, Name, 12DigitBarCode -first 20 |Out-String)" | |
$Choice = Read-Host "Enter You choice" | |
Write-Verbose "Calling REST API and Getting Nutrient composition" | |
# Extract the Nutrient Database number and Get Nutrient report from another REST API call | |
$Ndbno = ($result | ?{$_.choice -eq $Choice}).NutrientDBNo | |
$Food = (Invoke-RestMethod -Uri "http://api.nal.usda.gov/ndb/reports/?ndbno=$ndbno&type=b&format=json&api_key=nPEalh5PismxDHfVfSJ0VhSAG3uma32bgqO2RtEs").Report.food | |
cls | |
# Display Nutrient report | |
$Food.nutrients | ?{($_.value -as [double]) -gt 0} | select @{n='NutrientName';e={$_.Name}},` | |
@{n='Group';e={$_.group}},` | |
@{n='Value per 100g';e={$_.Value}},` | |
@{n='Unit';e={$_.unit}},` | |
@{n='Measures';e={$PV = $_;Foreach($Item in $pv.measures){"$([int]$Item.qty) "+$Item.Label+" = $($Item.value) "+$PV.unit}}} | |
} | |
Else | |
{ | |
Write-Host "Couldn't find an item that match `"$Query`", please try another name." -ForegroundColor Red | |
} | |
} | |
Get-Nutrient 'peanut butter' |ft -AutoSize | |
Get-Nutrient 'raw apple' | ft -AutoSize | |
Get-Nutrient 'coke' | ft -AutoSize |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment