2.7 KiB
2.7 KiB
Authentication
FastGPT API uses API keys for authentication. This guide covers how to securely manage and use your API keys with the SDK.
API Key Format
FastGPT API keys typically start with fastgpt-:
fastgpt-xxxxxxxxxxxxxxxxxxxxxx
Setting Your API Key
Method 1: Directly in Code (Not Recommended)
from fastgpt_client import ChatClient
client = ChatClient(api_key="fastgpt-xxxxx")
!!! warning Never commit API keys to version control!
Method 2: Environment Variables (Recommended)
Create a .env file:
API_KEY=fastgpt-xxxxx
BASE_URL=http://localhost:3000
Use python-dotenv to load it:
import os
from dotenv import load_dotenv
from fastgpt_client import ChatClient
load_dotenv()
client = ChatClient(
api_key=os.getenv("API_KEY"),
base_url=os.getenv("BASE_URL")
)
Add .env to your .gitignore:
.env
Method 3: System Environment Variables
Set the environment variable in your shell:
# Linux/macOS
export FASTGPT_API_KEY="fastgpt-xxxxx"
export FASTGPT_BASE_URL="http://localhost:3000"
# Windows (Command Prompt)
set FASTGPT_API_KEY=fastgpt-xxxxx
set FASTGPT_BASE_URL=http://localhost:3000
# Windows (PowerShell)
$env:FASTGPT_API_KEY="fastgpt-xxxxx"
$env:FASTGPT_BASE_URL="http://localhost:3000"
Then use it in Python:
import os
from fastgpt_client import ChatClient
client = ChatClient(
api_key=os.getenv("FASTGPT_API_KEY"),
base_url=os.getenv("FASTGPT_BASE_URL", "http://localhost:3000")
)
Base URL Configuration
The default base URL is http://localhost:3000. If you're using a different FastGPT instance:
client = ChatClient(
api_key="fastgpt-xxxxx",
base_url="https://your-fastgpt-instance.com"
)
Authentication Errors
If authentication fails, the SDK raises an AuthenticationError:
from fastgpt_client import ChatClient
from fastgpt_client.exceptions import AuthenticationError
try:
with ChatClient(api_key="invalid-key") as client:
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Hello"}]
)
except AuthenticationError as e:
print(f"Authentication failed: {e}")
Security Best Practices
- Never expose API keys in client-side code (browsers, mobile apps)
- Use environment variables to store keys
- Rotate keys regularly for production applications
- Use separate keys for different environments (dev, staging, prod)
- Monitor usage to detect unauthorized access
- Commit
.envto.gitignoreto prevent accidental commits
Next Steps
- Quick Start - Start using the SDK
- Error Handling - Learn to handle errors properly