> ## Documentation Index
> Fetch the complete documentation index at: https://docs.switchport.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Authenticate with the Switchport API using your API key

## Get Your API Key

<Steps>
  <Step title="Sign in to Switchport">
    Go to [switchport.ai](https://switchport.ai) and log in to your account.
  </Step>

  <Step title="Navigate to API Keys">
    Go to **Settings** → **API Keys** in the dashboard.
  </Step>

  <Step title="Copy your API key">
    Copy your API key. It should start with `sp_`.
  </Step>
</Steps>

## Set Your API Key

There are two ways to authenticate with the Switchport API:

### Option 1: Environment Variable (Recommended)

Set the `SWITCHPORT_API_KEY` environment variable:

<CodeGroup>
  ```bash Linux/Mac theme={null}
  export SWITCHPORT_API_KEY=sp_your_key_here
  ```

  ```powershell Windows (PowerShell) theme={null}
  $env:SWITCHPORT_API_KEY="sp_your_key_here"
  ```

  ```bash .env file theme={null}
  SWITCHPORT_API_KEY=sp_your_key_here
  ```
</CodeGroup>

Then initialize the client with an empty string:

```go theme={null}
package main

import (
	"log"

	"github.com/switchport-ai/switchport-go/switchport"
)

func main() {
	// Automatically reads from SWITCHPORT_API_KEY environment variable
	client, err := switchport.NewClient("")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Use client...
}
```

### Option 2: Pass API Key Directly

Pass the API key when creating the client:

```go theme={null}
package main

import (
	"log"

	"github.com/switchport-ai/switchport-go/switchport"
)

func main() {
	client, err := switchport.NewClient("sp_your_key_here")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Use client...
}
```

<Warning>
  Never hard-code API keys in your source code. Use environment variables or a secrets management system instead.
</Warning>

## Using .env Files

For local development, you can use a `.env` file with a library like `godotenv`:

1. Install godotenv:

```bash theme={null}
go get github.com/joho/godotenv
```

2. Create a `.env` file in your project root:

```bash theme={null}
SWITCHPORT_API_KEY=sp_your_key_here
```

3. Load the environment variables in your code:

```go theme={null}
package main

import (
	"log"

	"github.com/joho/godotenv"
	"github.com/switchport-ai/switchport-go/switchport"
)

func main() {
	// Load .env file
	err := godotenv.Load()
	if err != nil {
		log.Println("Warning: .env file not found")
	}

	// Reads from environment
	client, err := switchport.NewClient("")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Use client...
}
```

<Note>
  Add `.env` to your `.gitignore` file to avoid committing secrets to version control.
</Note>

## Configure API URL (Optional)

By default, the SDK connects to `https://switchport-api.vercel.app`. For local development or self-hosted instances, you can override this:

### Using Environment Variable

```bash theme={null}
export SWITCHPORT_API_URL=http://localhost:8001
```

The SDK will automatically read this environment variable.

### Passing to Client

```go theme={null}
client, err := switchport.NewClient("sp_your_key_here")
if err != nil {
	log.Fatalf("Failed to create client: %v", err)
}

// Override the base URL
client.BaseURL = "http://localhost:8001"
```

## Error Handling

If authentication fails, the SDK returns an `AuthenticationError`:

```go theme={null}
package main

import (
	"errors"
	"log"

	"github.com/switchport-ai/switchport-go/switchport"
)

func main() {
	client, err := switchport.NewClient("")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	response, err := client.Prompts.Execute("my-prompt", nil, nil)
	if err != nil {
		var authErr *switchport.AuthenticationError
		if errors.As(err, &authErr) {
			log.Printf("Authentication failed: %v", authErr)
			// Handle error (e.g., prompt user to check API key)
			return
		}
		log.Fatalf("Other error: %v", err)
	}

	log.Println(response.Text)
}
```

Common authentication errors:

* **Invalid API key**: The API key is incorrect or has been revoked
* **Missing API key**: No API key provided and `SWITCHPORT_API_KEY` is not set
* **Expired API key**: The API key has expired (contact support)

## API Key Validation

The SDK validates your API key format when creating the client:

```go theme={null}
client, err := switchport.NewClient("invalid_key")
if err != nil {
	// Error: API key must start with 'sp_'
	log.Printf("Validation error: %v", err)
}
```

API keys must:

* Start with `sp_`
* Be non-empty

## Security Best Practices

<AccordionGroup>
  <Accordion title="Use environment variables">
    Store API keys in environment variables, not in source code.
  </Accordion>

  <Accordion title="Rotate keys regularly">
    Regularly rotate API keys to minimize risk if a key is compromised.
  </Accordion>

  <Accordion title="Use different keys for different environments">
    Use separate API keys for development, staging, and production.
  </Accordion>

  <Accordion title="Restrict key permissions">
    If available, use API keys with limited permissions for specific use cases.
  </Accordion>

  <Accordion title="Never commit secrets">
    Add `.env` and secrets files to `.gitignore`.
  </Accordion>

  <Accordion title="Use secrets management in production">
    In production, use proper secrets management solutions like AWS Secrets Manager, HashiCorp Vault, or Kubernetes secrets.
  </Accordion>
</AccordionGroup>

## Next Steps

<Card title="Execute Prompts" icon="code" href="/sdk/go/prompts">
  Learn how to execute prompts with the SDK
</Card>
