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

# Authentication

> Secure API access with API keys for all Solvice optimization services

## Overview

The Solvice Platform uses API key authentication to secure access to all optimization endpoints. Every request to our solvers requires a valid API key included in the request headers.

<Info>
  All API communications are encrypted using HTTPS to ensure your data and credentials remain secure during transmission.
</Info>

## Getting Your API Key

<Steps>
  <Step title="Sign up for Solvice">
    Create your account at [platform.solvice.io](https://platform.solvice.io) if you haven't already.

    <Note>
      New accounts receive a 14-day free trial with full access to all solver capabilities.
    </Note>
  </Step>

  <Step title="Navigate to API Keys">
    Once logged in, go to **Settings** → **API Keys** in your dashboard.

    <Frame caption="API Keys section in the Solvice Dashboard">
      <img src="https://mintcdn.com/solvice-68592f22/noMIHjSWP2Tg_tTz/images/api-keys.png?fit=max&auto=format&n=noMIHjSWP2Tg_tTz&q=85&s=100117624d6002e8eb411044ffa7da64" alt="Solvice Dashboard API Keys management interface showing the Create API Key button" width="1513" height="1018" data-path="images/api-keys.png" />
    </Frame>
  </Step>

  <Step title="Generate a new key">
    Click **Create API Key** and provide a descriptive name for your key (e.g., "Production VRP Integration").

    <Warning>
      Store your API key securely. For security reasons, you won't be able to view the full key again after creation.
    </Warning>
  </Step>

  <Step title="Configure key permissions">
    Select which solvers and operations this key can access:

    * **Solver access**: VRP, FILL, CREATE, TASK, CLUST
    * **Operations**: Solve, Evaluate, Suggest, Status, Solution, Explanation

    <Tip>
      Follow the principle of least privilege - only grant permissions required for your specific use case.
    </Tip>
  </Step>
</Steps>

## Using Your API Key

Include your API key in the `Authorization` header of every request to Solvice APIs.

### Authentication Header Format

```
Authorization: YOUR_API_KEY
```

<Warning>
  The API key should be sent directly in the Authorization header without any prefix like "Bearer" or "Basic".
</Warning>

### Request Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST 'https://api.solvice.io/v2/vrp/solve' \
    -H 'Authorization: YOUR_API_KEY' \
    -H 'Content-Type: application/json' \
    -d '{
      "vehicles": [...],
      "jobs": [...],
      "objectives": [...]
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://api.solvice.io/v2/vrp/solve', {
    method: 'POST',
    headers: {
      'Authorization': process.env.SOLVICE_API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(requestData)
  });

  if (!response.ok) {
    throw new Error(`API request failed: ${response.status}`);
  }

  const result = await response.json();
  ```

  ```python Python theme={null}
  import os
  import requests

  api_key = os.environ.get('SOLVICE_API_KEY')

  response = requests.post(
      'https://api.solvice.io/v2/vrp/solve',
      headers={
          'Authorization': api_key,
          'Content-Type': 'application/json'
      },
      json=request_data
  )

  if response.status_code != 200:
      raise Exception(f'API request failed: {response.status_code}')

  result = response.json()
  ```

  ```java Java theme={null}
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;

  HttpClient client = HttpClient.newHttpClient();

  HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://api.solvice.io/v2/vrp/solve"))
      .header("Authorization", System.getenv("SOLVICE_API_KEY"))
      .header("Content-Type", "application/json")
      .POST(HttpRequest.BodyPublishers.ofString(requestJson))
      .build();

  HttpResponse<String> response = client.send(request, 
      HttpResponse.BodyHandlers.ofString());
  ```

  ```csharp C# theme={null}
  using var client = new HttpClient();
  client.DefaultRequestHeaders.Add("Authorization", 
      Environment.GetEnvironmentVariable("SOLVICE_API_KEY"));

  var response = await client.PostAsJsonAsync(
      "https://api.solvice.io/v2/vrp/solve", 
      requestData
  );

  response.EnsureSuccessStatusCode();
  var result = await response.Content.ReadFromJsonAsync<SolveResponse>();
  ```
</CodeGroup>

## Authentication Errors

When authentication fails, the API returns specific error codes to help diagnose the issue:

```json 401 Unauthorized theme={null}
{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing API key",
    "details": "Please check your Authorization header"
  }
}
```

### Common Authentication Issues

<AccordionGroup>
  <Accordion title="401 Unauthorized - Missing API Key">
    **Problem**: No API key provided in the request

    **Solution**: Ensure the `Authorization` header is included in your request

    ```bash theme={null}
    # ❌ Missing Authorization header
    curl -X POST 'https://api.solvice.io/v2/vrp/solve'

    # ✅ Correct
    curl -X POST 'https://api.solvice.io/v2/vrp/solve' \
      -H 'Authorization: YOUR_API_KEY'
    ```
  </Accordion>

  <Accordion title="401 Unauthorized - Invalid API Key">
    **Problem**: The provided API key is invalid or has been revoked

    **Solution**:

    * Verify you're using the correct API key
    * Check if the key has been accidentally truncated
    * Ensure the key hasn't been revoked in your dashboard
  </Accordion>

  <Accordion title="403 Forbidden - Insufficient Permissions">
    **Problem**: Your API key doesn't have permission for the requested operation

    **Solution**: Check your key's permissions in the dashboard and ensure it has access to:

    * The specific solver (VRP, FILL, etc.)
    * The operation type (solve, evaluate, suggest)
  </Accordion>

  <Accordion title="429 Too Many Requests">
    **Problem**: You've exceeded your rate limit

    **Solution**:

    * Implement exponential backoff in your retry logic
    * Check your current rate limits in the dashboard
    * Consider upgrading your plan for higher limits
  </Accordion>
</AccordionGroup>

## Security Best Practices

<Steps>
  <Step title="Environment Variables">
    Never hardcode API keys in your source code. Use environment variables instead:

    ```bash .env theme={null}
    SOLVICE_API_KEY=your_api_key_here
    ```

    <Warning>
      Add `.env` files to your `.gitignore` to prevent accidental commits
    </Warning>
  </Step>

  <Step title="Key Rotation">
    Regularly rotate your API keys, especially for production environments:

    * Set up a rotation schedule (e.g., every 90 days)
    * Update keys during maintenance windows
    * Keep the previous key active briefly during transition
  </Step>

  <Step title="Separate Keys by Environment">
    Use different API keys for different environments:

    ```javascript theme={null}
    const apiKey = process.env.NODE_ENV === 'production' 
      ? process.env.SOLVICE_PROD_KEY
      : process.env.SOLVICE_DEV_KEY;
    ```
  </Step>

  <Step title="Monitor Key Usage">
    Regularly review your API key usage in the dashboard:

    * Check for unexpected usage patterns
    * Monitor which endpoints are being called
    * Set up alerts for unusual activity
  </Step>

  <Step title="Restrict Key Permissions">
    Apply the principle of least privilege:

    * Development keys: Limited to non-production solvers
    * Production keys: Only required solvers and operations
    * CI/CD keys: Read-only access for testing
  </Step>
</Steps>

## Server-Side Proxy Pattern

For web applications, implement a server-side proxy to keep your API keys secure:

<Tabs>
  <Tab title="Node.js Express">
    ```javascript server.js theme={null}
    const express = require('express');
    const app = express();

    // Never expose API keys to client-side code
    const SOLVICE_API_KEY = process.env.SOLVICE_API_KEY;

    app.post('/api/solve', async (req, res) => {
      try {
        const response = await fetch('https://api.solvice.io/v2/vrp/solve', {
          method: 'POST',
          headers: {
            'Authorization': SOLVICE_API_KEY,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(req.body)
        });
        
        const data = await response.json();
        res.json(data);
      } catch (error) {
        res.status(500).json({ error: 'Internal server error' });
      }
    });
    ```
  </Tab>

  <Tab title="Python Flask">
    ```python app.py theme={null}
    from flask import Flask, request, jsonify
    import requests
    import os

    app = Flask(__name__)
    SOLVICE_API_KEY = os.environ.get('SOLVICE_API_KEY')

    @app.route('/api/solve', methods=['POST'])
    def solve():
        try:
            response = requests.post(
                'https://api.solvice.io/v2/vrp/solve',
                headers={
                    'Authorization': SOLVICE_API_KEY,
                    'Content-Type': 'application/json'
                },
                json=request.json
            )
            return jsonify(response.json()), response.status_code
        except Exception as e:
            return jsonify({'error': 'Internal server error'}), 500
    ```
  </Tab>

  <Tab title="Client-Side">
    ```javascript frontend.js theme={null}
    // Client makes requests to your server, not directly to Solvice
    const response = await fetch('/api/solve', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(optimizationRequest)
    });

    // No API key needed on client side
    const result = await response.json();
    ```
  </Tab>
</Tabs>

## Rate Limiting

Solvice implements rate limiting to ensure fair usage and platform stability:

<Tabs>
  <Tab title="Rate Limit Headers">
    Every API response includes rate limit information:

    ```
    X-RateLimit-Limit: 100
    X-RateLimit-Remaining: 95
    X-RateLimit-Reset: 1609459200
    ```

    <ParamField header="X-RateLimit-Limit" type="integer">
      Maximum requests allowed in the current window
    </ParamField>

    <ParamField header="X-RateLimit-Remaining" type="integer">
      Number of requests remaining in the current window
    </ParamField>

    <ParamField header="X-RateLimit-Reset" type="integer">
      Unix timestamp when the rate limit window resets
    </ParamField>
  </Tab>

  <Tab title="Handling Rate Limits">
    ```javascript theme={null}
    async function makeRequestWithRetry(url, options, maxRetries = 3) {
      for (let i = 0; i < maxRetries; i++) {
        const response = await fetch(url, options);
        
        if (response.status === 429) {
          const resetTime = response.headers.get('X-RateLimit-Reset');
          const waitTime = resetTime 
            ? (parseInt(resetTime) * 1000) - Date.now()
            : Math.pow(2, i) * 1000; // Exponential backoff
          
          console.log(`Rate limited. Waiting ${waitTime}ms...`);
          await new Promise(resolve => setTimeout(resolve, waitTime));
          continue;
        }
        
        return response;
      }
      
      throw new Error('Max retries exceeded');
    }
    ```
  </Tab>
</Tabs>

## SDK Authentication

Our official SDKs handle authentication details for you:

<Tabs>
  <Tab title="JavaScript/TypeScript">
    ```typescript theme={null}
    import { SolviceClient } from '@solvice/sdk';

    const client = new SolviceClient({
      apiKey: process.env.SOLVICE_API_KEY,
      // SDK handles all authentication headers
    });

    const result = await client.vrp.solve({
      vehicles: [...],
      jobs: [...]
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from solvice import SolviceClient

    client = SolviceClient(
        api_key=os.environ.get('SOLVICE_API_KEY')
    )

    result = client.vrp.solve(
        vehicles=[...],
        jobs=[...]
    )
    ```
  </Tab>

  <Tab title="Java">
    ```java theme={null}
    SolviceClient client = SolviceClient.builder()
        .apiKey(System.getenv("SOLVICE_API_KEY"))
        .build();

    SolveResponse result = client.vrp().solve(
        SolveRequest.builder()
            .vehicles(vehicles)
            .jobs(jobs)
            .build()
    );
    ```
  </Tab>
</Tabs>

## Testing Authentication

Use our test endpoint to verify your API key is working correctly:

<CodeGroup>
  ```bash cURL theme={null}
  curl 'https://api.solvice.io/v2/auth/verify' \
    -H 'Authorization: YOUR_API_KEY'
  ```

  ```javascript Response theme={null}
  {
    "valid": true,
    "key_name": "Production VRP Integration",
    "permissions": {
      "solvers": ["vrp", "fill"],
      "operations": ["solve", "status", "solution"]
    },
    "rate_limit": {
      "requests_per_hour": 1000,
      "concurrent_jobs": 10
    }
  }
  ```
</CodeGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Quick Start" icon="rocket" href="/guides/vrp/quickstart">
    Start optimizing routes with your API key
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore all available endpoints
  </Card>

  <Card title="SDKs" icon="cube" href="/guides/platform/sdks">
    Use our official SDK libraries
  </Card>

  <Card title="Dashboard" icon="chart-line" href="https://platform.solvice.io">
    Manage your API keys and usage
  </Card>
</CardGroup>
