Files
fastgpt-python-sdk/docs/getting_started/authentication.md
2026-01-08 17:35:21 +08:00

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

from fastgpt_client import ChatClient

client = ChatClient(api_key="fastgpt-xxxxx")

!!! warning Never commit API keys to version control!

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

  1. Never expose API keys in client-side code (browsers, mobile apps)
  2. Use environment variables to store keys
  3. Rotate keys regularly for production applications
  4. Use separate keys for different environments (dev, staging, prod)
  5. Monitor usage to detect unauthorized access
  6. Commit .env to .gitignore to prevent accidental commits

Next Steps