1+ """Module for interacting with the Codeflash API."""
2+
13from __future__ import annotations
24
35import json
1416from pydantic .json import pydantic_encoder
1517
1618from codeflash .cli_cmds .console import console , logger
19+ from codeflash .code_utils .code_utils import exit_with_message
1720from codeflash .code_utils .env_utils import ensure_codeflash_api_key , get_codeflash_api_key , get_pr_number
1821from codeflash .code_utils .git_utils import get_current_branch , get_repo_owner_and_name
1922from codeflash .github .PrComment import FileDiffContent , PrComment
@@ -101,13 +104,18 @@ def make_cfapi_request(
101104def get_user_id (api_key : Optional [str ] = None ) -> Optional [str ]:
102105 """Retrieve the user's userid by making a request to the /cfapi/cli-get-user endpoint.
103106
107+ :param api_key: The API key to use. If None, uses get_codeflash_api_key().
104108 :return: The userid or None if the request fails.
105109 """
106110 if not api_key and not ensure_codeflash_api_key ():
107111 return None
108112
109113 response = make_cfapi_request (
110- endpoint = "/cli-get-user" , method = "GET" , extra_headers = {"cli_version" : __version__ }, api_key = api_key
114+ endpoint = "/cli-get-user" ,
115+ method = "GET" ,
116+ extra_headers = {"cli_version" : __version__ },
117+ api_key = api_key ,
118+ suppress_errors = True ,
111119 )
112120 if response .status_code == 200 :
113121 if "min_version" not in response .text :
@@ -128,6 +136,20 @@ def get_user_id(api_key: Optional[str] = None) -> Optional[str]:
128136 logger .error ("Failed to retrieve userid from the response." )
129137 return None
130138
139+ # Handle 403 (Invalid API key) - exit with error message
140+ if response .status_code == 403 :
141+ msg = (
142+ "Invalid Codeflash API key. The API key you provided is not valid.\n "
143+ "Please generate a new one at https://app.codeflash.ai/app/apikeys ,\n "
144+ "then set it as a CODEFLASH_API_KEY environment variable.\n "
145+ "For more information, refer to the documentation at \n "
146+ "https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#manual-setup\n "
147+ "or\n "
148+ "https://docs.codeflash.ai/optimizing-with-codeflash/codeflash-github-actions#automated-setup-recommended"
149+ )
150+ exit_with_message (msg , error_on_exit = True )
151+
152+ # For other errors, log and return None (backward compatibility)
131153 logger .error (f"Failed to look up your userid; is your CF API key valid? ({ response .reason } )" )
132154 return None
133155
0 commit comments