This Bash script allows you to check whether an OpenAI API key is valid. It sends a request to the OpenAI API and verifies the HTTP response status code. If the key is valid, it returns a confirmation message. Otherwise, it informs you that the key is invalid or that there was an issue with the request.
Run the script with the API key as an argument:
./check_openai_key.sh <API_KEY>
Replace <API_KEY>
with your actual OpenAI API key.
#!/bin/bash
# Function to check key validity
function check_key_validity() {
local key=$1
local response
response=$(curl -s -o /dev/null -w "%{http_code}" https://api.openai.com/v1/models -H "Authorization: Bearer $key")
if [ "$response" -eq 200 ]; then
echo "β
The API key is valid."
else
echo "β The API key is invalid or there was a problem with the request. (HTTP Code: $response)"
fi
}
# Main script: Check if an API key was provided
if [ $# -ne 1 ]; then
echo "Usage: $0 <API-Key>"
exit 1
fi
API_KEY=$1
# Perform key validation
check_key_validity "$API_KEY"
- Requires
curl
to be installed on your system. - Ensure the API key has the necessary permissions and is still active.
You can copy and paste this script into a file (e.g., check_openai_key.sh
), make it executable with:
chmod +x check_openai_key.sh
Then, run it with your API key.
Enjoy! π