calorie-api 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ from ._version import __version__
2
+ from .client import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, CalorieApi, normalize_rapidapi_host
3
+ from .errors import CalorieApiError, ErrorKind
4
+ from .models import (
5
+ ActivityLevel,
6
+ BarcodeLookupResult,
7
+ BarcodeMicronutrient,
8
+ BarcodeNutrition,
9
+ BarcodeProduct,
10
+ BarcodeServing,
11
+ FoodBarcode,
12
+ FoodDetails,
13
+ FoodNutrient,
14
+ FoodSearchPage,
15
+ FoodSearchResult,
16
+ FoodSuggestion,
17
+ Gender,
18
+ Goal,
19
+ Ingredient,
20
+ MacroCalcResult,
21
+ MacroTargets,
22
+ MatchMode,
23
+ Meal,
24
+ MealMacros,
25
+ Mode,
26
+ NutrientItem,
27
+ Portion,
28
+ PortionCalcResult,
29
+ PortionNutrition,
30
+ RecipeCalcResult,
31
+ RecipeTotals,
32
+ )
33
+
34
+ __all__ = [
35
+ "__version__",
36
+ "DEFAULT_BASE_URL",
37
+ "DEFAULT_TIMEOUT",
38
+ "CalorieApi",
39
+ "CalorieApiError",
40
+ "ErrorKind",
41
+ "normalize_rapidapi_host",
42
+ "ActivityLevel",
43
+ "BarcodeLookupResult",
44
+ "BarcodeMicronutrient",
45
+ "BarcodeNutrition",
46
+ "BarcodeProduct",
47
+ "BarcodeServing",
48
+ "FoodBarcode",
49
+ "FoodDetails",
50
+ "FoodNutrient",
51
+ "FoodSearchPage",
52
+ "FoodSearchResult",
53
+ "FoodSuggestion",
54
+ "Gender",
55
+ "Goal",
56
+ "Ingredient",
57
+ "MacroCalcResult",
58
+ "MacroTargets",
59
+ "MatchMode",
60
+ "Meal",
61
+ "MealMacros",
62
+ "Mode",
63
+ "NutrientItem",
64
+ "Portion",
65
+ "PortionCalcResult",
66
+ "PortionNutrition",
67
+ "RecipeCalcResult",
68
+ "RecipeTotals",
69
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
calorie_api/client.py ADDED
@@ -0,0 +1,468 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import os
6
+ import re
7
+ import socket
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from datetime import datetime, timezone
12
+ from email.utils import parsedate_to_datetime
13
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union, cast
14
+
15
+ from ._version import __version__
16
+ from .errors import CalorieApiError
17
+ from .models import (
18
+ ActivityLevel,
19
+ BarcodeLookupResult,
20
+ FoodDetails,
21
+ FoodSearchPage,
22
+ FoodSuggestion,
23
+ Gender,
24
+ Goal,
25
+ Ingredient,
26
+ MacroCalcResult,
27
+ MatchMode,
28
+ Mode,
29
+ PortionCalcResult,
30
+ RecipeCalcResult,
31
+ )
32
+
33
+ DEFAULT_BASE_URL = "https://calorieapiadmin.com"
34
+ DEFAULT_TIMEOUT = 30.0
35
+
36
+ _API_PREFIX = "/api/v1"
37
+ _DEMO_PREFIX = "/api/v1/public"
38
+ _LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
39
+ _RAPIDAPI_HOST_PATTERN = re.compile(r"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+rapidapi\.com")
40
+ _API_SUFFIX_PATTERN = re.compile(r"/api/v1(?:/public)?$")
41
+ _VALIDATION_LOCATIONS = frozenset({"query", "body", "path", "header"})
42
+ _MISSING_KEY_MESSAGE = (
43
+ "Missing API key. Pass api_key, set CALORIE_API_KEY, or pass demo=True to try the public demo. "
44
+ "Get a free key at https://calorieapi.com/auth/register"
45
+ )
46
+
47
+ IngredientInput = Union[Ingredient, Mapping[str, Any], Tuple[int, float]]
48
+
49
+
50
+ class _RefuseRedirects(urllib.request.HTTPRedirectHandler):
51
+ def redirect_request(
52
+ self,
53
+ req: urllib.request.Request,
54
+ fp: Any,
55
+ code: int,
56
+ msg: str,
57
+ headers: Any,
58
+ newurl: str,
59
+ ) -> Optional[urllib.request.Request]:
60
+ return None
61
+
62
+
63
+ def _invalid(message: str) -> CalorieApiError:
64
+ return CalorieApiError(message, kind="invalid_argument")
65
+
66
+
67
+ def _clean(value: Any) -> Optional[str]:
68
+ if not isinstance(value, str):
69
+ return None
70
+ stripped = value.strip()
71
+ return stripped or None
72
+
73
+
74
+ def normalize_rapidapi_host(host: Optional[str]) -> str:
75
+ value = (_clean(host) or "").lower()
76
+ if not value:
77
+ raise _invalid("rapidapi_host is required with rapidapi_key, for example your-api.p.rapidapi.com")
78
+ if "://" in value:
79
+ try:
80
+ value = urllib.parse.urlsplit(value).hostname or ""
81
+ except ValueError:
82
+ value = ""
83
+ else:
84
+ value = value.split("/")[0].split(":")[0]
85
+ if not _RAPIDAPI_HOST_PATTERN.fullmatch(value):
86
+ raise _invalid("rapidapi_host must be a RapidAPI host such as your-api.p.rapidapi.com")
87
+ return value
88
+
89
+
90
+ def _normalize_base_url(raw: Any) -> str:
91
+ if not isinstance(raw, str):
92
+ raise _invalid("base_url must be a string")
93
+ try:
94
+ parts = urllib.parse.urlsplit(raw.strip())
95
+ hostname = parts.hostname
96
+ _ = parts.port
97
+ except ValueError:
98
+ raise _invalid(f"base_url is not a valid URL: {raw}") from None
99
+ if not parts.scheme or not hostname:
100
+ raise _invalid(f"base_url is not a valid URL: {raw}")
101
+ is_local = hostname in _LOCAL_HOSTS
102
+ if not (parts.scheme == "https" or (parts.scheme == "http" and is_local)):
103
+ raise _invalid("base_url must use https (http is allowed only for localhost)")
104
+ if parts.query or parts.fragment or parts.username or parts.password:
105
+ raise _invalid("base_url must not contain a query string, fragment or credentials")
106
+ path = parts.path.rstrip("/")
107
+ if _API_SUFFIX_PATTERN.search(path):
108
+ raise _invalid("base_url is the API origin, for example https://calorieapiadmin.com, without /api/v1")
109
+ return f"{parts.scheme}://{parts.netloc}{path}"
110
+
111
+
112
+ def _require_str(value: Any, name: str) -> str:
113
+ if not isinstance(value, str):
114
+ raise _invalid(f"{name} must be a string")
115
+ return value.strip()
116
+
117
+
118
+ def _require_positive_int(value: Any, name: str) -> int:
119
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
120
+ raise _invalid(f"{name} must be a positive integer")
121
+ return value
122
+
123
+
124
+ def _require_number(value: Any, name: str) -> float:
125
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
126
+ raise _invalid(f"{name} must be a finite number")
127
+ return value
128
+
129
+
130
+ def _ingredient(item: Any, index: int) -> Dict[str, Any]:
131
+ if isinstance(item, Mapping):
132
+ food_id, grams = item.get("food_id"), item.get("grams")
133
+ elif isinstance(item, (tuple, list)) and len(item) == 2:
134
+ food_id, grams = item
135
+ else:
136
+ raise _invalid(
137
+ f"ingredients[{index}] must be a mapping with food_id and grams, or a (food_id, grams) pair"
138
+ )
139
+ return {
140
+ "food_id": _require_positive_int(food_id, f"ingredients[{index}].food_id"),
141
+ "grams": _require_number(grams, f"ingredients[{index}].grams"),
142
+ }
143
+
144
+
145
+ def _query_value(value: Any) -> str:
146
+ if isinstance(value, bool):
147
+ return "true" if value else "false"
148
+ return str(value)
149
+
150
+
151
+ def _extract_detail(payload: Any) -> Any:
152
+ if isinstance(payload, str):
153
+ return payload
154
+ if not isinstance(payload, dict):
155
+ return None
156
+ for key in ("detail", "message", "error"):
157
+ if payload.get(key) is not None:
158
+ return payload[key]
159
+ return None
160
+
161
+
162
+ def _format_validation_item(item: Any) -> Optional[str]:
163
+ if isinstance(item, str):
164
+ return item
165
+ if not isinstance(item, dict):
166
+ return None
167
+ message = item.get("msg") if isinstance(item.get("msg"), str) else item.get("message")
168
+ if not isinstance(message, str):
169
+ return json.dumps(item)
170
+ location = item.get("loc")
171
+ if isinstance(location, list):
172
+ parts = [str(part) for part in location]
173
+ if parts and parts[0] in _VALIDATION_LOCATIONS:
174
+ parts = parts[1:]
175
+ if parts:
176
+ return f"{'.'.join(parts)}: {message}"
177
+ return message
178
+
179
+
180
+ def _format_detail(detail: Any) -> Optional[str]:
181
+ if isinstance(detail, str):
182
+ return detail.strip() or None
183
+ if isinstance(detail, list):
184
+ parts = [text for text in (_format_validation_item(item) for item in detail) if text]
185
+ return "; ".join(parts) or None
186
+ if isinstance(detail, dict):
187
+ for key in ("message", "msg"):
188
+ if isinstance(detail.get(key), str):
189
+ return cast(str, detail[key])
190
+ return json.dumps(detail)
191
+ return None
192
+
193
+
194
+ def _retry_after(value: Optional[str]) -> Optional[int]:
195
+ if not value or not value.strip():
196
+ return None
197
+ text = value.strip()
198
+ try:
199
+ seconds = float(text)
200
+ except ValueError:
201
+ seconds = None
202
+ if seconds is not None:
203
+ if math.isfinite(seconds) and seconds >= 0:
204
+ return math.ceil(seconds)
205
+ return None
206
+ try:
207
+ when = parsedate_to_datetime(text)
208
+ except (TypeError, ValueError, IndexError):
209
+ return None
210
+ if when is None:
211
+ return None
212
+ if when.tzinfo is None:
213
+ when = when.replace(tzinfo=timezone.utc)
214
+ return max(0, math.ceil((when - datetime.now(timezone.utc)).total_seconds()))
215
+
216
+
217
+ def _decode_json(raw: bytes) -> Tuple[bool, Any]:
218
+ if not raw:
219
+ return False, None
220
+ try:
221
+ return True, json.loads(raw.decode("utf-8"))
222
+ except (UnicodeDecodeError, ValueError):
223
+ return False, None
224
+
225
+
226
+ def _http_error(error: urllib.error.HTTPError) -> CalorieApiError:
227
+ status = error.code
228
+ try:
229
+ raw = error.read()
230
+ except Exception:
231
+ raw = b""
232
+ parsed, payload = _decode_json(raw if isinstance(raw, bytes) else b"")
233
+ detail = _extract_detail(payload) if parsed else None
234
+ headers = error.headers
235
+ retry_after = _retry_after(headers.get("Retry-After") if headers is not None else None)
236
+ if 300 <= status < 400:
237
+ reason = "redirects are not followed, check base_url"
238
+ else:
239
+ reason = _format_detail(detail) or (str(error.reason).strip() if error.reason else "") or "request failed"
240
+ return CalorieApiError(
241
+ f"Calorie API returned {status}: {reason}",
242
+ status=status,
243
+ detail=detail,
244
+ retry_after=retry_after,
245
+ )
246
+
247
+
248
+ class CalorieApi:
249
+ def __init__(
250
+ self,
251
+ api_key: Optional[str] = None,
252
+ *,
253
+ rapidapi_key: Optional[str] = None,
254
+ rapidapi_host: Optional[str] = None,
255
+ demo: bool = False,
256
+ base_url: Optional[str] = None,
257
+ timeout: float = DEFAULT_TIMEOUT,
258
+ ) -> None:
259
+ rapid_key = _clean(rapidapi_key)
260
+ direct_key = _clean(api_key)
261
+ if direct_key is None and rapid_key is None:
262
+ direct_key = _clean(os.environ.get("CALORIE_API_KEY"))
263
+
264
+ headers = {
265
+ "Accept": "application/json",
266
+ "User-Agent": f"calorie-api-python/{__version__}",
267
+ }
268
+ default_base_url = DEFAULT_BASE_URL
269
+ mode: Mode
270
+ if rapid_key:
271
+ host = normalize_rapidapi_host(rapidapi_host)
272
+ mode = "rapidapi"
273
+ prefix = _API_PREFIX
274
+ default_base_url = f"https://{host}"
275
+ headers["X-RapidAPI-Key"] = rapid_key
276
+ headers["X-RapidAPI-Host"] = host
277
+ elif direct_key:
278
+ mode = "direct"
279
+ prefix = _API_PREFIX
280
+ headers["X-API-Key"] = direct_key
281
+ elif demo:
282
+ mode = "demo"
283
+ prefix = _DEMO_PREFIX
284
+ else:
285
+ raise _invalid(_MISSING_KEY_MESSAGE)
286
+
287
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(timeout) or timeout <= 0:
288
+ raise _invalid("timeout must be a positive number of seconds")
289
+
290
+ self.mode: Mode = mode
291
+ self.base_url = default_base_url if base_url is None else _normalize_base_url(base_url)
292
+ self.timeout = float(timeout)
293
+ self._prefix = prefix
294
+ self._headers = headers
295
+ self._opener = urllib.request.build_opener(_RefuseRedirects)
296
+
297
+ def __repr__(self) -> str:
298
+ return f"CalorieApi(mode={self.mode!r}, base_url={self.base_url!r})"
299
+
300
+ def search_foods(
301
+ self,
302
+ query: str,
303
+ *,
304
+ limit: Optional[int] = None,
305
+ skip: Optional[int] = None,
306
+ match_mode: Optional[MatchMode] = None,
307
+ verified_only: Optional[bool] = None,
308
+ brand: Optional[str] = None,
309
+ brand_id: Optional[int] = None,
310
+ category: Optional[str] = None,
311
+ category_id: Optional[int] = None,
312
+ nutrient_id: Optional[int] = None,
313
+ min_amount: Optional[float] = None,
314
+ max_amount: Optional[float] = None,
315
+ min_calories: Optional[float] = None,
316
+ max_calories: Optional[float] = None,
317
+ min_protein: Optional[float] = None,
318
+ max_protein: Optional[float] = None,
319
+ min_carbs: Optional[float] = None,
320
+ max_carbs: Optional[float] = None,
321
+ min_fat: Optional[float] = None,
322
+ max_fat: Optional[float] = None,
323
+ ) -> FoodSearchPage:
324
+ params: Dict[str, Any] = {
325
+ "q": _require_str(query, "query"),
326
+ "limit": limit,
327
+ "skip": skip,
328
+ "match_mode": match_mode,
329
+ "verified_only": verified_only,
330
+ "brand": brand,
331
+ "brand_id": brand_id,
332
+ "category": category,
333
+ "category_id": category_id,
334
+ "nutrient_id": nutrient_id,
335
+ "min_amount": min_amount,
336
+ "max_amount": max_amount,
337
+ "min_calories": min_calories,
338
+ "max_calories": max_calories,
339
+ "min_protein": min_protein,
340
+ "max_protein": max_protein,
341
+ "min_carbs": min_carbs,
342
+ "max_carbs": max_carbs,
343
+ "min_fat": min_fat,
344
+ "max_fat": max_fat,
345
+ }
346
+ return cast(FoodSearchPage, self._request("GET", "/search/foods", query=params))
347
+
348
+ def suggest_foods(self, query: str, *, limit: Optional[int] = None) -> List[FoodSuggestion]:
349
+ text = _require_str(query, "query")
350
+ if not text:
351
+ raise _invalid("query must not be empty")
352
+ return cast(
353
+ List[FoodSuggestion],
354
+ self._request("GET", "/search/suggest", query={"q": text, "limit": limit}),
355
+ )
356
+
357
+ def lookup_barcode(self, barcode: str) -> BarcodeLookupResult:
358
+ digits = re.sub(r"\D", "", _require_str(barcode, "barcode"))
359
+ if not digits:
360
+ raise _invalid("barcode must contain digits")
361
+ return cast(BarcodeLookupResult, self._request("GET", f"/search/barcode/{digits}"))
362
+
363
+ def get_food(self, food_id: int) -> FoodDetails:
364
+ _require_positive_int(food_id, "food_id")
365
+ return cast(FoodDetails, self._request("GET", f"/foods/{food_id}"))
366
+
367
+ def calc_macros(
368
+ self,
369
+ *,
370
+ age: int,
371
+ gender: Gender,
372
+ weight_kg: float,
373
+ height_cm: float,
374
+ activity: ActivityLevel,
375
+ goal: Goal,
376
+ ) -> MacroCalcResult:
377
+ params = {
378
+ "age": age,
379
+ "gender": gender,
380
+ "weight_kg": weight_kg,
381
+ "height_cm": height_cm,
382
+ "activity": activity,
383
+ "goal": goal,
384
+ }
385
+ for name, value in params.items():
386
+ if value is None:
387
+ raise _invalid(f"{name} is required")
388
+ return cast(MacroCalcResult, self._request("GET", "/calc/macros", query=params))
389
+
390
+ def calc_portion(self, food_id: int, grams: float) -> PortionCalcResult:
391
+ params = {
392
+ "food_id": _require_positive_int(food_id, "food_id"),
393
+ "grams": _require_number(grams, "grams"),
394
+ }
395
+ return cast(PortionCalcResult, self._request("GET", "/calc/portion", query=params))
396
+
397
+ def calc_recipe(
398
+ self,
399
+ ingredients: Sequence[IngredientInput],
400
+ *,
401
+ servings: Optional[int] = None,
402
+ ) -> RecipeCalcResult:
403
+ if isinstance(ingredients, (str, bytes)) or not isinstance(ingredients, Sequence) or not ingredients:
404
+ raise _invalid("ingredients must be a non-empty list")
405
+ body: Dict[str, Any] = {
406
+ "ingredients": [_ingredient(item, index) for index, item in enumerate(ingredients)],
407
+ }
408
+ if servings is not None:
409
+ body["servings"] = _require_positive_int(servings, "servings")
410
+ return cast(RecipeCalcResult, self._request("POST", "/calc/recipe", body=body))
411
+
412
+ def _build_url(self, path: str, query: Optional[Mapping[str, Any]]) -> str:
413
+ url = f"{self.base_url}{self._prefix}{path}"
414
+ pairs = [(name, _query_value(value)) for name, value in (query or {}).items() if value is not None]
415
+ if pairs:
416
+ url = f"{url}?{urllib.parse.urlencode(pairs)}"
417
+ return url
418
+
419
+ def _request(
420
+ self,
421
+ method: str,
422
+ path: str,
423
+ *,
424
+ query: Optional[Mapping[str, Any]] = None,
425
+ body: Any = None,
426
+ ) -> Any:
427
+ headers = dict(self._headers)
428
+ data = None
429
+ if body is not None:
430
+ data = json.dumps(body).encode("utf-8")
431
+ headers["Content-Type"] = "application/json"
432
+ request = urllib.request.Request(
433
+ self._build_url(path, query),
434
+ data=data,
435
+ headers=headers,
436
+ method=method,
437
+ )
438
+ try:
439
+ with self._opener.open(request, timeout=self.timeout) as response:
440
+ status = int(getattr(response, "status", None) or response.getcode())
441
+ raw = response.read()
442
+ except urllib.error.HTTPError as error:
443
+ raise _http_error(error) from None
444
+ except urllib.error.URLError as error:
445
+ if isinstance(error.reason, (socket.timeout, TimeoutError)):
446
+ raise self._timeout_error() from error
447
+ raise CalorieApiError(
448
+ f"Could not reach Calorie API: {error.reason}", kind="network_error"
449
+ ) from error
450
+ except (socket.timeout, TimeoutError) as error:
451
+ raise self._timeout_error() from error
452
+ except OSError as error:
453
+ raise CalorieApiError(f"Could not reach Calorie API: {error}", kind="network_error") from error
454
+
455
+ parsed, payload = _decode_json(raw)
456
+ if not parsed:
457
+ raise CalorieApiError(
458
+ f"Calorie API returned {status} with a body that is not JSON",
459
+ kind="invalid_response",
460
+ status=status,
461
+ )
462
+ return payload
463
+
464
+ def _timeout_error(self) -> CalorieApiError:
465
+ return CalorieApiError(
466
+ f"Calorie API did not respond within {self.timeout:g} seconds",
467
+ kind="timeout",
468
+ )
calorie_api/errors.py ADDED
@@ -0,0 +1,29 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Literal, Optional
4
+
5
+ ErrorKind = Literal[
6
+ "http_error",
7
+ "timeout",
8
+ "network_error",
9
+ "invalid_response",
10
+ "invalid_argument",
11
+ ]
12
+
13
+
14
+ class CalorieApiError(Exception):
15
+ def __init__(
16
+ self,
17
+ message: str,
18
+ *,
19
+ kind: ErrorKind = "http_error",
20
+ status: Optional[int] = None,
21
+ detail: Any = None,
22
+ retry_after: Optional[int] = None,
23
+ ) -> None:
24
+ super().__init__(message)
25
+ self.message = message
26
+ self.kind = kind
27
+ self.status = status
28
+ self.detail = detail
29
+ self.retry_after = retry_after
calorie_api/models.py ADDED
@@ -0,0 +1,226 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import List, Literal, Optional, TypedDict
4
+
5
+ Mode = Literal["direct", "rapidapi", "demo"]
6
+ Gender = Literal["male", "female"]
7
+ ActivityLevel = Literal[
8
+ "sedentary",
9
+ "lightly_active",
10
+ "moderately_active",
11
+ "very_active",
12
+ "extra_active",
13
+ ]
14
+ Goal = Literal["lose", "maintain", "gain"]
15
+ MatchMode = Literal["any", "all"]
16
+
17
+
18
+ class Ingredient(TypedDict):
19
+ food_id: int
20
+ grams: float
21
+
22
+
23
+ class NutrientItem(TypedDict):
24
+ nutrient_id: int
25
+ nutrient_name: str
26
+ amount: float
27
+
28
+
29
+ class Portion(TypedDict):
30
+ grams: float
31
+ label: str
32
+
33
+
34
+ class MealMacros(TypedDict):
35
+ protein: float
36
+ carbs: float
37
+ fat: float
38
+ fiber: float
39
+ sugar: float
40
+
41
+
42
+ class Meal(TypedDict):
43
+ name: str
44
+ calories: float
45
+ servings: int
46
+ macros: MealMacros
47
+
48
+
49
+ class _FoodSearchResultRequired(TypedDict):
50
+ id: int
51
+ name: str
52
+ is_verified: bool
53
+ match_type: Optional[str]
54
+ search_score: Optional[float]
55
+ description: Optional[str]
56
+ serving_size: Optional[float]
57
+ serving_unit: Optional[str]
58
+ serving: Optional[str]
59
+ brand_name: Optional[str]
60
+ category_name: Optional[str]
61
+ created_at: Optional[str]
62
+ nutrients: List[NutrientItem]
63
+ upc: Optional[str]
64
+ calories_100g: float
65
+ protein_100g: float
66
+ carbs_100g: float
67
+ fat_100g: float
68
+ fiber_100g: float
69
+ sugar_100g: float
70
+ meal: Meal
71
+
72
+
73
+ class FoodSearchResult(_FoodSearchResultRequired, total=False):
74
+ portion_nutrients: Optional[List[NutrientItem]]
75
+ default_portion: Optional[Portion]
76
+ portions_count: int
77
+ match_rank: Optional[int]
78
+
79
+
80
+ class FoodSearchPage(TypedDict):
81
+ data: List[FoodSearchResult]
82
+ total: int
83
+ skip: int
84
+ limit: int
85
+
86
+
87
+ class FoodSuggestion(TypedDict):
88
+ id: int
89
+ name: str
90
+ brand_name: Optional[str]
91
+
92
+
93
+ class BarcodeProduct(TypedDict):
94
+ name: str
95
+ brand: Optional[str]
96
+ category: Optional[str]
97
+ generic_name: Optional[str]
98
+ quantity: Optional[str]
99
+ ingredients: Optional[str]
100
+ allergens: List[str]
101
+
102
+
103
+ class BarcodeServing(TypedDict):
104
+ label: Optional[str]
105
+ quantity: Optional[float]
106
+ unit: Optional[str]
107
+
108
+
109
+ class BarcodeNutrition(TypedDict):
110
+ energy_kcal: Optional[float]
111
+ protein_g: Optional[float]
112
+ carbohydrates_g: Optional[float]
113
+ fat_g: Optional[float]
114
+ fiber_g: Optional[float]
115
+ sugars_g: Optional[float]
116
+ saturated_fat_g: Optional[float]
117
+ salt_g: Optional[float]
118
+ sodium_g: Optional[float]
119
+ added_sugars_g: Optional[float]
120
+
121
+
122
+ class BarcodeMicronutrient(TypedDict):
123
+ name: str
124
+ amount: float
125
+ unit: str
126
+
127
+
128
+ class BarcodeLookupResult(TypedDict):
129
+ barcode: str
130
+ food_id: Optional[int]
131
+ product: BarcodeProduct
132
+ serving: BarcodeServing
133
+ nutrition_per_100g: BarcodeNutrition
134
+ nutrition_per_serving: Optional[BarcodeNutrition]
135
+ micronutrients_per_100g: List[BarcodeMicronutrient]
136
+
137
+
138
+ class FoodNutrient(TypedDict):
139
+ nutrient_id: int
140
+ name: str
141
+ unit: str
142
+ amount: float
143
+
144
+
145
+ class FoodBarcode(TypedDict):
146
+ barcode_value: str
147
+ barcode_type: str
148
+
149
+
150
+ class _FoodDetailsRequired(TypedDict):
151
+ id: int
152
+ name: str
153
+ nutrients: List[FoodNutrient]
154
+ barcodes: List[FoodBarcode]
155
+
156
+
157
+ class FoodDetails(_FoodDetailsRequired, total=False):
158
+ description: Optional[str]
159
+ brand_id: Optional[int]
160
+ category_id: Optional[int]
161
+ brand_name: Optional[str]
162
+ category_name: Optional[str]
163
+ is_verified: bool
164
+ serving_size: Optional[float]
165
+ serving_unit: Optional[str]
166
+ serving: Optional[str]
167
+ calories_100g: float
168
+ protein_100g: float
169
+ carbs_100g: float
170
+ fat_100g: float
171
+ fiber_100g: float
172
+ sugar_100g: float
173
+ portions_count: int
174
+ default_portion: Optional[Portion]
175
+ verified_portions: List[Portion]
176
+ suggested_serving: Optional[Portion]
177
+
178
+
179
+ class MacroTargets(TypedDict):
180
+ calories: int
181
+ protein_g: float
182
+ carbohydrates_g: float
183
+ fat_g: float
184
+
185
+
186
+ class MacroCalcResult(TypedDict):
187
+ bmr: int
188
+ tdee: int
189
+ activity_multiplier: float
190
+ daily_targets: MacroTargets
191
+ formula: str
192
+
193
+
194
+ class PortionNutrition(TypedDict):
195
+ calories: Optional[float]
196
+ protein_g: Optional[float]
197
+ carbohydrates_g: Optional[float]
198
+ fat_g: Optional[float]
199
+ fiber_g: Optional[float]
200
+ sugars_g: Optional[float]
201
+ saturated_fat_g: Optional[float]
202
+ sodium_g: Optional[float]
203
+
204
+
205
+ class PortionCalcResult(TypedDict):
206
+ food_id: int
207
+ food_name: str
208
+ requested_grams: float
209
+ nutrition: PortionNutrition
210
+
211
+
212
+ class RecipeTotals(TypedDict):
213
+ calories: float
214
+ protein_g: float
215
+ carbohydrates_g: float
216
+ fat_g: float
217
+ fiber_g: float
218
+ sugars_g: float
219
+
220
+
221
+ class RecipeCalcResult(TypedDict):
222
+ servings: int
223
+ total: RecipeTotals
224
+ per_serving: RecipeTotals
225
+ ingredients_resolved: int
226
+
calorie_api/py.typed ADDED
File without changes
@@ -0,0 +1,249 @@
1
+ Metadata-Version: 2.4
2
+ Name: calorie-api
3
+ Version: 0.1.0
4
+ Summary: Calorie API client for Python. Nutrition API for food search, barcode lookup, nutrient data, macro targets, portions and recipe nutrition across 6.8M+ foods.
5
+ Author: BusyBody FIT LTD
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://calorieapi.com/nutrition-api
8
+ Project-URL: Documentation, https://calorieapi.com/docs
9
+ Project-URL: Pricing, https://calorieapi.com/pricing
10
+ Project-URL: Repository, https://github.com/Busybody1/calorie-api-sdk
11
+ Keywords: nutrition api,calorie api,food database,barcode,macros,nutrition,calories,food api,food search,upc,recipe nutrition,tdee
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Internet :: WWW/HTTP
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Dynamic: license-file
29
+
30
+ # Calorie API for Python
31
+
32
+ The official Python client for **Calorie API**, the [nutrition API](https://calorieapi.com/nutrition-api) for 6.8M+ foods. Search foods, look up barcodes, read full nutrient data, and calculate macro targets, portion nutrition and recipe totals from one small, typed, zero-dependency package.
33
+
34
+ - Docs: [calorieapi.com/docs](https://calorieapi.com/docs)
35
+ - Pricing: [calorieapi.com/pricing](https://calorieapi.com/pricing)
36
+ - Free API key: [calorieapi.com/auth/register](https://calorieapi.com/auth/register)
37
+ - Try it in the browser: [calorieapi.com/playground](https://calorieapi.com/playground)
38
+
39
+ Python 3.9 or newer. Standard library only (`urllib`). Fully type hinted, with `TypedDict` response types.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install calorie-api
45
+ ```
46
+
47
+ ## Quick start
48
+
49
+ ```python
50
+ from calorie_api import CalorieApi
51
+
52
+ api = CalorieApi("your_api_key")
53
+
54
+ page = api.search_foods("chicken breast", limit=5)
55
+ for food in page["data"]:
56
+ print(food["id"], food["name"], food["calories_100g"], "kcal per 100 g")
57
+ ```
58
+
59
+ If you leave out the key, the client reads the `CALORIE_API_KEY` environment variable. Requests go to `https://calorieapiadmin.com/api/v1` with your key in the `X-API-Key` header.
60
+
61
+ ## Endpoints
62
+
63
+ | Method | HTTP endpoint |
64
+ | --- | --- |
65
+ | `search_foods(query, **filters)` | `GET /api/v1/search/foods` |
66
+ | `suggest_foods(query, limit=None)` | `GET /api/v1/search/suggest` |
67
+ | `lookup_barcode(barcode)` | `GET /api/v1/search/barcode/{upc}` |
68
+ | `get_food(food_id)` | `GET /api/v1/foods/{food_id}` |
69
+ | `calc_macros(age=, gender=, weight_kg=, height_cm=, activity=, goal=)` | `GET /api/v1/calc/macros` |
70
+ | `calc_portion(food_id, grams)` | `GET /api/v1/calc/portion` |
71
+ | `calc_recipe(ingredients, servings=None)` | `POST /api/v1/calc/recipe` |
72
+
73
+ Every method returns the parsed JSON response as plain dicts and lists, typed with the `TypedDict` classes exported from `calorie_api` (`FoodSearchPage`, `FoodDetails`, `BarcodeLookupResult`, `MacroCalcResult` and so on). Keyword names match the API parameter names.
74
+
75
+ ### Search foods
76
+
77
+ ```python
78
+ page = api.search_foods(
79
+ "greek yogurt",
80
+ limit=10,
81
+ skip=0,
82
+ verified_only=True,
83
+ max_calories=120,
84
+ )
85
+
86
+ print(page["total"])
87
+ first = page["data"][0]
88
+ print(first["name"], first["brand_name"])
89
+ print(first["calories_100g"], first["protein_100g"], first["carbs_100g"], first["fat_100g"])
90
+ print(first["nutrients"])
91
+ ```
92
+
93
+ Returns `{"data", "total", "skip", "limit"}`. Each result has per 100 g values (`calories_100g`, `protein_100g`, `carbs_100g`, `fat_100g`, `fiber_100g`, `sugar_100g`), a `nutrients` list, serving info and a `meal` dict scaled to the default serving.
94
+
95
+ Keyword filters:
96
+
97
+ | Keyword | Notes |
98
+ | --- | --- |
99
+ | `limit` | 1 to 100, default 30. Your plan caps the results per search. |
100
+ | `skip` | Offset for paging |
101
+ | `match_mode` | `"any"` (default) or `"all"` words |
102
+ | `verified_only` | Only verified foods |
103
+ | `brand`, `brand_id` | Filter by brand |
104
+ | `category`, `category_id` | Filter by category |
105
+ | `nutrient_id`, `min_amount`, `max_amount` | Require a nutrient in a range |
106
+ | `min_calories`, `max_calories` | Calories per 100 g |
107
+ | `min_protein`, `max_protein` | Grams per 100 g |
108
+ | `min_carbs`, `max_carbs` | Grams per 100 g |
109
+ | `min_fat`, `max_fat` | Grams per 100 g |
110
+
111
+ An empty query (`""`) returns common foods.
112
+
113
+ ### Autocomplete
114
+
115
+ ```python
116
+ suggestions = api.suggest_foods("chi", limit=8)
117
+ # [{"id": ..., "name": ..., "brand_name": ...}, ...]
118
+ ```
119
+
120
+ ### Barcode lookup
121
+
122
+ ```python
123
+ product = api.lookup_barcode("3017620422003")
124
+ print(product["product"]["name"], product["product"]["brand"])
125
+ print(product["nutrition_per_100g"]["energy_kcal"], product["nutrition_per_100g"]["protein_g"])
126
+ print(product["micronutrients_per_100g"])
127
+ ```
128
+
129
+ UPC and EAN codes are accepted as strings. Spaces and dashes are removed before the request. An unknown barcode raises `CalorieApiError` with status 404.
130
+
131
+ ### Food details
132
+
133
+ ```python
134
+ food = api.get_food(first["id"])
135
+ print(food["name"], food["nutrients"], food["barcodes"], food.get("verified_portions"))
136
+ ```
137
+
138
+ ### Macro targets (TDEE)
139
+
140
+ ```python
141
+ macros = api.calc_macros(
142
+ age=28,
143
+ gender="male",
144
+ weight_kg=80,
145
+ height_cm=178,
146
+ activity="moderately_active",
147
+ goal="maintain",
148
+ )
149
+
150
+ print(macros["bmr"], macros["tdee"])
151
+ print(macros["daily_targets"])
152
+ # {"calories", "protein_g", "carbohydrates_g", "fat_g"}
153
+ ```
154
+
155
+ `gender` is `"male"` or `"female"`. `activity` is `"sedentary"`, `"lightly_active"`, `"moderately_active"`, `"very_active"` or `"extra_active"`. `goal` is `"lose"`, `"maintain"` or `"gain"`. The API uses the Mifflin-St Jeor formula.
156
+
157
+ ### Portion nutrition
158
+
159
+ ```python
160
+ portion = api.calc_portion(first["id"], 150)
161
+ print(portion["food_name"], portion["requested_grams"], portion["nutrition"])
162
+ # nutrition: calories, protein_g, carbohydrates_g, fat_g, fiber_g, sugars_g, saturated_fat_g, sodium_g
163
+ ```
164
+
165
+ ### Recipe nutrition
166
+
167
+ ```python
168
+ recipe = api.calc_recipe(
169
+ [
170
+ {"food_id": 12345, "grams": 300},
171
+ (67890, 200),
172
+ ],
173
+ servings=4,
174
+ )
175
+
176
+ print(recipe["total"]["calories"], recipe["per_serving"]["calories"], recipe["ingredients_resolved"])
177
+ ```
178
+
179
+ Each ingredient is a dict with `food_id` and `grams`, or a `(food_id, grams)` tuple. Up to 50 ingredients and 1 to 100 servings (default 1). `ingredients_resolved` counts the ingredients found in the database.
180
+
181
+ ## Error handling
182
+
183
+ Every failure raises `CalorieApiError`:
184
+
185
+ ```python
186
+ from calorie_api import CalorieApi, CalorieApiError
187
+
188
+ try:
189
+ api.get_food(999999999)
190
+ except CalorieApiError as error:
191
+ print(error) # "Calorie API returned 404: Food not found"
192
+ print(error.status) # 404, or None when no response arrived
193
+ print(error.kind) # "http_error"
194
+ print(error.detail) # the API's "detail" value
195
+ print(error.retry_after) # seconds to wait, from Retry-After, or None
196
+ ```
197
+
198
+ | `kind` | When |
199
+ | --- | --- |
200
+ | `http_error` | The API answered with a non-2xx status. The message includes the status and the API's error message. |
201
+ | `timeout` | No response within `timeout` seconds |
202
+ | `network_error` | DNS, TLS or connection failure |
203
+ | `invalid_response` | A 2xx response that was not JSON |
204
+ | `invalid_argument` | A bad argument, caught before any request was sent |
205
+
206
+ Common statuses: `401` for a missing or wrong key, `402` when your monthly quota is used up, `403` when your plan does not cover the request, `404` when a food or barcode is not found, `422` for out-of-range parameters (the message lists each field), and `429` when you go over your plan's per-minute rate limit.
207
+
208
+ ## Configuration
209
+
210
+ ```python
211
+ api = CalorieApi(
212
+ "your_key",
213
+ timeout=10,
214
+ base_url="https://calorieapiadmin.com",
215
+ )
216
+ ```
217
+
218
+ | Argument | Default | Notes |
219
+ | --- | --- | --- |
220
+ | `api_key` | `CALORIE_API_KEY` env var | Your Calorie API key |
221
+ | `timeout` | `30.0` | Per request timeout in seconds |
222
+ | `base_url` | `https://calorieapiadmin.com` | API origin, without `/api/v1`. Must be https, except for localhost. |
223
+ | `demo` | `False` | Use the keyless public demo when no key is set |
224
+
225
+ The client never follows redirects, so your key is only sent to the host you configured. It honors the standard `HTTPS_PROXY` and `NO_PROXY` environment variables.
226
+
227
+ ### Public demo (no key)
228
+
229
+ ```python
230
+ demo = CalorieApi(demo=True)
231
+ page = demo.search_foods("apple", limit=5)
232
+ ```
233
+
234
+ The demo uses the `/api/v1/public/...` routes, which are limited to 30 requests per hour per IP address and one request per second, with at most 10 results per search. Use it to try the API, then switch to a free key.
235
+
236
+ ## Pricing
237
+
238
+ The free tier includes 1,000 API calls a month. Paid plans start at $15 a month for 20,000 calls. Each plan also sets a rate limit and a cap on results per search (20 foods per search on the free plan). Commercial apps need the Plus or Enterprise plan. See [calorieapi.com/pricing](https://calorieapi.com/pricing) for current plans.
239
+
240
+ ## Links
241
+
242
+ - [Nutrition API overview](https://calorieapi.com/nutrition-api)
243
+ - [API documentation](https://calorieapi.com/docs)
244
+ - [Pricing](https://calorieapi.com/pricing)
245
+ - [Get a free API key](https://calorieapi.com/auth/register)
246
+
247
+ ## License
248
+
249
+ MIT. Copyright (c) 2026 BusyBody FIT LTD.
@@ -0,0 +1,11 @@
1
+ calorie_api/__init__.py,sha256=q0frf59eshr462sW2y6vOJlMKNCw4B1kCejEpg612Bk,1400
2
+ calorie_api/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
3
+ calorie_api/client.py,sha256=El-9Mm6mEhm1UhvEEIjw16jVn9RVyE-xmVukNP2PAts,16391
4
+ calorie_api/errors.py,sha256=062xwEoe7iZeD-mUHf6Ig24lbtzG0qRB0U1ECLe_vUk,656
5
+ calorie_api/models.py,sha256=-Xy-p8xBJcwI6ryXVRRPrZRJdheKQoH0i6YTaAvliWM,4762
6
+ calorie_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ calorie_api-0.1.0.dist-info/licenses/LICENSE,sha256=8habjUqdKNBgqlryO20XefOENRX2wLjSs0Vb9VnLJ64,1073
8
+ calorie_api-0.1.0.dist-info/METADATA,sha256=VtcIc1BCvbSPbLgUsJ-xfhsI6kaW_Rk2BqROzO-9r-0,9554
9
+ calorie_api-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ calorie_api-0.1.0.dist-info/top_level.txt,sha256=vFbc0q-jYceJ4_1zsnu58vkQGJCUbwbl9h1ZNOq4Mo4,12
11
+ calorie_api-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BusyBody FIT LTD
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ calorie_api