Missing Scope or API Not Resolved ERROR

68 views
Skip to first unread message

aitel

unread,
Apr 27, 2025, 10:04:47 PMApr 27
to fatsecret Platform API
Request Payload: {'image_b64': '<base64_image>', 'output_format': 'json', 'include_food_data': True, 'region': 'US', 'language': 'en', 'eaten_foods': []}
Response Status Code: 200
Response Text: {"error":{"code":"14","message":"Missing scope: scope 'image-recognition'"}}
127.0.0.1 - - [27/Apr/2025 12:33:55] "POST /upload HTTP/1.1" 200 -


The above is the Response I got for the Below Code even though I have a Premier Account Image Recognition is not working for me can someone help me out to fix this and help me to use the image recognition api

CODE :

def get_access_token():
    """
    Obtain an OAuth2 token with the correct scopes.
    You MUST have 'image-recognition' scope enabled on your FatSecret account.
    """
    global token, token_expiry
    # Only request new token if expired or not present
    if token and token_expiry and datetime.now(timezone.utc) < token_expiry:
        return token

    auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
    # Request both scopes; this will fail if 'image-recognition' is not enabled for your client
    data = {'grant_type': 'client_credentials', 'scope': 'premier image-recognition'}
    response = requests.post(TOKEN_URL, auth=auth, data=data)
    if response.status_code == 400 and 'invalid_scope' in response.text:
        raise Exception(
            "Your FatSecret client is not enabled for the 'image-recognition' scope. "
            "Contact FatSecret support to enable this feature for your account."
        )
    response.raise_for_status()
    token_data = response.json()
    token = token_data['access_token']
    token_expiry = datetime.now(timezone.utc) + timedelta(seconds=token_data['expires_in'] - 60)
    return token

def process_image(file_storage):
    """
    Convert uploaded image to optimized base64-encoded JPEG.
    """
    img = Image.open(file_storage.stream)
    img = img.convert('RGB')
    # Resize to max 1024x1024 for API efficiency
    if max(img.size) > 1024:
        img.thumbnail((1024, 1024))
    buffer = BytesIO()
    img.save(buffer, format="JPEG", quality=85)
    buffer.seek(0)
    img_bytes = buffer.read()
    img_base64 = base64.b64encode(img_bytes).decode('utf-8')
    # FatSecret API limit: 1,148,549 characters
    if len(img_base64) > 1148549:
        raise ValueError("Image is too large after encoding. Please upload a smaller image.")
    return img_base64

def recognize_food(base64_image, access_token):
    """
    Call the FatSecret image recognition API.
    """
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    payload = {
        "image_b64": base64_image,
        "output_format": "json",
        "include_food_data": True,
        "region": "US",
        "language": "en",
        "eaten_foods": []
    }
    response = requests.post(IMAGE_API_URL, headers=headers, json=payload)
    print("Request Payload:", {k: (v if k != "image_b64" else "<base64_image>") for k, v in payload.items()})
    print("Response Status Code:", response.status_code)
    print("Response Text:", response.text)
    if response.status_code == 200 and not response.text.strip():
        return {"food_recognition_results": []}
    response.raise_for_status()
    return response.json()

seba...@fatsecret.com

unread,
Apr 27, 2025, 10:05:49 PMApr 27
to fatsecret Platform API
Thanks for reaching out. As with all AI powered solutions, there are high infrastructure costs associated hence both Image Recognition and Natural Language Processing (while optional) are billed per usage. Please get in touch with our API support team to have these enabled:
Reply all
Reply to author
Forward
0 new messages