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

# API Responses

> Understand response formats, HTTP status codes, and error handling in the GameBoost API

## Response Format

All API responses follow a consistent JSON structure, making it easy to parse and handle responses in your application.

### Success Responses

Successful requests return a `200` status code with the requested data:

```json theme={null}
{
  "data": {
    "id": "order_abc123",
    "status": "completed",
    "created_at": "2025-10-11T10:30:00Z"
  },
  "request_id": "0e8400-e29b..."
}
```

### Error Responses

Failed requests return an appropriate error status code with detailed error information:

```json theme={null}
{
    "message": "Invalid request parameters",
    "errors": {
        "login": "The 'login' field is required"
    },
    "request_id": "0e8400-e29b..."
}
```

<Note>
  Always include the `request_id` when contacting support. This helps us quickly locate and troubleshoot your specific request.
</Note>

## HTTP Status Codes

The GameBoost API uses standard HTTP status codes to indicate the success or failure of requests.

### Success Codes

| Status Code | Meaning              | Description                              |
| ----------- | -------------------- | ---------------------------------------- |
| `200`       | Success              | Request completed successfully           |
| `204`       | Success (No Content) | Request successful but no data to return |

### Client Error Codes

These errors indicate issues with your request or authentication

| Status Code                | Meaning               | Likely Reason                                                       |
| -------------------------- | --------------------- | ------------------------------------------------------------------- |
| `400 Bad Request`          | Invalid Request       | The request syntax is malformed or contains invalid parameters      |
| `401 Unauthorized`         | Authentication Failed | Missing, invalid, or expired API key                                |
| `403 Forbidden`            | Access Denied         | Valid authentication but insufficient permissions for this resource |
| `404 Not Found`            | Resource Not Found    | The requested resource doesn't exist or you don't have access to it |
| `422 Unprocessable Entity` | Validation Failed     | Request syntax is correct but data validation failed                |
| `429 Too Many Requests`    | Rate Limited          | You've exceeded the rate limit. Slow down your requests             |

### Server Error Codes

These errors indicate issues on our servers or infrastructure

| Status Code                 | Meaning         | Likely Reason                                                            |
| --------------------------- | --------------- | ------------------------------------------------------------------------ |
| `500 Internal Server Error` | Server Error    | An unexpected error occurred on our servers. Try again later             |
| `502 Bad Gateway`           | Gateway Error   | Temporary issue with our infrastructure. Retry with exponential backoff  |
| `503 Service Unavailable`   | Service Down    | The service is temporarily unavailable. Check our status page            |
| `504 Gateway Timeout`       | Request Timeout | The request took too long to process. Try again or simplify your request |

## Error Response Examples

### 401 Unauthorized

**Cause**: Missing or invalid authentication credentials.

<CodeGroup>
  ```json 401 Unauthorized theme={null}
  {
    "message": "Unauthorized access",
    "request_id": "0e8400-e29b..."
  }
  ```
</CodeGroup>

**How to fix**: Ensure you're including a valid API key in the Authorization header. See our [Authentication Guide](/api/get-started/authentication).

### 403 Forbidden

**Cause**: You don't have permission to access this resource.

<CodeGroup>
  ```json 403 Forbidden theme={null}
  {
      "message": "Unauthorized access",
      "request_id": "0e8400-e29b..."
  }
  ```
</CodeGroup>

**How to fix**: Verify the resource you're trying to access belongs to you.

### 404 Not Found

**Cause**: The requested resource doesn't exist or you don't have access to it.

<CodeGroup>
  ```json 404 Not Found theme={null}
  {
      "message": "Resource not found",
      "request_id": "0e8400-e29b..."
  }
  ```
</CodeGroup>

**How to fix**: Double-check the resource ID in your request. Ensure the resource exists and you have access to it.

### 422 Unprocessable Entity

**Cause**: Request validation failed due to invalid data.

<CodeGroup>
  ```json 422 Validation Error theme={null}
  {
      "message": "The account data is invalid",
      "errors": {
          "credentials.email_login": "The credentials.email_login field must be a valid email address",
          "account_data.server": "The account_data.server field must be one of: EU, US, etc."
      },
      "request_id": "0e8400-e29b...",
  }
  ```
</CodeGroup>

**How to fix**: Review the `errors` object and correct the specified fields.

### 429 Too Many Requests

**Cause**: You've exceeded the API rate limit.

<CodeGroup>
  ```json 429 Rate Limited theme={null}
  {
      "message": "Too many requests",
      "request_id": "0e8400-e29b..."
  }
  ```
</CodeGroup>

**How to fix**: Implement exponential backoff and respect the `Retry-After` header. See our [Rate Limiting Guide](/api/get-started/rate-limiting).

### 500 Internal Server Error

**Cause**: An unexpected error occurred on GameBoost's servers.

<CodeGroup>
  ```json 500 Server Error theme={null}
  {
      "message": "An internal server error occurred",
      "request_id": "0e8400-e29b..."
  }
  ```
</CodeGroup>

**How to fix**: This is an issue on our end. Try again in a few moments. If the problem persists, contact us with the `request_id`.

### 503 Service Unavailable

**Cause**: The API is temporarily unavailable, usually due to maintenance.

<CodeGroup>
  ```json 503 Service Unavailable theme={null}
  {
      "message": "Service temporarily unavailable",
      "request_id": "0e8400-e29b...",
  }
  ```
</CodeGroup>

**How to fix**: Wait for the specified `Retry-After` seconds and try again. Check our [status page](https://status.gameboost.com) for updates.

## Handling Errors

### Best Practices

<AccordionGroup>
  <Accordion title="Always check status codes">
    Don't rely solely on the presence of data in the response. Always check the HTTP status code to determine if the request was successful.

    ```javascript theme={null}
    const response = await fetch('https://api.gameboost.com/v2/orders', {
      headers: { 'Authorization': `Bearer ${apiKey}` }
    });

    if (!response.ok) {
      const errorData = await response.json();
      console.error(`Error ${response.status}:`, errorData.message);
      console.error(`Request ID:`, errorData.request_id);
      throw new Error(errorData.message);
    }

    const data = await response.json();
    ```
  </Accordion>

  <Accordion title="Parse error details">
    Extract useful information from error responses to provide better feedback to users or for debugging.

    ```javascript theme={null}
    try {
      const response = await fetch(url, options);
      if (!response.ok) {
        const errorData = await response.json();

        // Log the request_id for support
        console.error('Request ID:', errorData.request_id);

        // Handle specific error types
        if (response.status === 429) {
          // Rate limited - check headers for retry timing
          const retryAfter = response.headers.get('Retry-After');
          await sleep(parseInt(retryAfter) * 1000);
          return retry();
        }

        if (response.status === 422 && errorData.errors) {
          // Validation errors
          return handleValidationErrors(errorData.errors);
        }

        // Generic error
        throw new Error(errorData.message);
      }
    } catch (error) {
      console.error('API request failed:', error);
    }
    ```
  </Accordion>

  <Accordion title="Implement retry logic">
    For transient errors (5xx status codes), implement retry logic with exponential backoff.

    ```javascript theme={null}
    async function apiRequestWithRetry(url, options, maxRetries = 3) {
      for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
          const response = await fetch(url, options);

          if (response.ok) {
            return await response.json();
          }

          // Retry on server errors
          if (response.status >= 500) {
            const backoff = Math.pow(2, attempt) * 1000;
            console.log(`Server error, retrying in ${backoff}ms...`);
            await sleep(backoff);
            continue;
          }

          // Don't retry client errors
          const error = await response.json();
          throw new Error(error.message);

        } catch (error) {
          if (attempt === maxRetries - 1) throw error;
        }
      }
    }
    ```
  </Accordion>

  <Accordion title="Log request IDs">
    Always log the `request_id` from error responses. This is invaluable when contacting support.

    ```javascript theme={null}
    function logError(errorData, response, context) {
      console.error({
        timestamp: new Date().toISOString(),
        request_id: errorData.request_id,
        status_code: response.status,
        message: errorData.message,
        errors: errorData.errors,
        context: context
      });
    }
    ```
  </Accordion>
</AccordionGroup>

## Response Headers

All API responses include helpful headers for debugging and rate limiting:

| Header                   | Description                                                   |
| ------------------------ | ------------------------------------------------------------- |
| `X-Gameboost-Request-Id` | Unique identifier for this request (same as in response body) |
| `X-RateLimit-Limit`      | Your rate limit cap for this endpoint type                    |
| `X-RateLimit-Remaining`  | Number of requests remaining in the current window            |
| `X-Ratelimit-Reset`      | Unix timestamp when the rate limit resets                     |
| `Retry-After`            | Seconds to wait before retrying (only when rate limited)      |

<Tip>
  Monitor the `X-RateLimit-Remaining` header to implement proactive rate limiting in your application.
</Tip>

## Next Steps

<CardGroup cols={2}>
  <Card title="Rate Limiting" icon="clock" href="/api/get-started/rate-limiting">
    Learn how to handle rate limits effectively
  </Card>

  <Card title="Webhooks" icon="webhook" href="/api/get-started/configure-webhooks">
    Set up real-time event notifications
  </Card>

  <Card title="API Reference" icon="book" href="/api/reference/account-offers/list-account-offers">
    Explore all available endpoints
  </Card>

  <Card title="Authentication" icon="key" href="/api/get-started/authentication">
    Review authentication setup
  </Card>
</CardGroup>
