Skip to content

Instantly share code, notes, and snippets.

@Friedjof
Created February 7, 2025 05:09
Show Gist options
  • Save Friedjof/94bfade9ac9163cc9e22c862edd6359e to your computer and use it in GitHub Desktop.
Save Friedjof/94bfade9ac9163cc9e22c862edd6359e to your computer and use it in GitHub Desktop.
πŸ›  OpenAI API Key Validator (Bash Script)

OpenAI API Key Validator Script

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.

Usage

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.

Script

#!/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"

Notes

  • 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! πŸš€

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment