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

# Stemfard API error codes, causes, and how to fix them

> HTTP status codes returned by the Stemfard API, the validation error response schema, and code examples for handling errors in your application.

When a request to the Stemfard API cannot be completed successfully, the API returns a non-200 HTTP status code and a JSON response body that describes what went wrong. Your application should always check the HTTP status code before processing a response, and handle error responses appropriately rather than assuming every response contains valid result data.

## HTTP status codes

| Status | Name                  | When it occurs                                                                                                                               |
| ------ | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `200`  | OK                    | The request succeeded. The response body contains the computed result.                                                                       |
| `401`  | Unauthorized          | The `Authorization` header is missing, malformed, or contains an invalid API key.                                                            |
| `422`  | Unprocessable Entity  | The request body failed validation — a required field is missing, a value is the wrong type, or a parameter value is not in the allowed set. |
| `500`  | Internal Server Error | An unexpected error occurred on the server. If this persists, contact support.                                                               |

## Validation error response (422)

When the API returns `422`, the response body follows this schema:

```json theme={null}
{
  "detail": [
    {
      "loc": ["body", "a"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}
```

The `detail` array contains one entry for each validation problem found in your request.

<ResponseField name="detail" type="object[]" required>
  Array of validation error objects. Contains one entry per field that failed validation.

  <Expandable title="properties">
    <ResponseField name="loc" type="string[]" required>
      Location of the invalid field as an array of path segments. The first element is always `"body"`, followed by the field name (e.g., `["body", "a"]`). For nested fields, the array contains each level of nesting.
    </ResponseField>

    <ResponseField name="msg" type="string" required>
      Human-readable description of the validation failure. Examples: `"field required"`, `"value is not a valid list"`, `"value is not a valid integer"`.
    </ResponseField>

    <ResponseField name="type" type="string" required>
      Machine-readable error type identifier. Examples: `"value_error.missing"`, `"type_error.list"`, `"type_error.integer"`.
    </ResponseField>
  </Expandable>
</ResponseField>

## Common validation errors

| Error type            | Cause                                            | Fix                                                |
| --------------------- | ------------------------------------------------ | -------------------------------------------------- |
| `value_error.missing` | A required field is absent from the request body | Add the missing field (commonly `a` or `b`)        |
| `type_error.list`     | A matrix field was not sent as a 2D array        | Ensure `a` and `b` are arrays of arrays of numbers |
| `value_error.const`   | An enum field received an unrecognised value     | Check the allowed values for `operation` or `type` |
| `type_error.integer`  | A numeric field received a non-integer value     | Check the type of `decimals` and similar fields    |

## Handling errors

The examples below show how to detect and handle error responses in your application.

<CodeGroup>
  ```bash cURL theme={null}
  # Check the HTTP status code with -w and -o
  curl --request POST \
    --url https://api.stemfard.com/api/v1/mathematics/linear-algebra/matrix-operations/matrix-arithmetic/add \
    --header 'Authorization: Bearer <your-api-key>' \
    --header 'Content-Type: application/json' \
    --data '{"b": [[1,2],[3,4]]}' \
    --silent \
    --output response.json \
    --write-out '%{http_code}'

  # Non-200 output: 422
  # response.json will contain the validation error detail
  ```

  ```javascript JavaScript theme={null}
  async function callStemfard(endpoint, body) {
    const response = await fetch(
      `https://api.stemfard.com/api/v1/mathematics/linear-algebra/matrix-operations/${endpoint}`,
      {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer <your-api-key>',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body),
      }
    );

    if (!response.ok) {
      const error = await response.json();

      if (response.status === 401) {
        throw new Error('Invalid or missing API key.');
      }

      if (response.status === 422) {
        const messages = error.detail
          .map(d => `${d.loc.join('.')}: ${d.msg}`)
          .join(', ');
        throw new Error(`Validation error — ${messages}`);
      }

      if (response.status === 500) {
        throw new Error('Stemfard server error. Please try again later.');
      }

      throw new Error(`Unexpected error: ${response.status}`);
    }

    return response.json();
  }
  ```

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

  def call_stemfard(endpoint: str, body: dict) -> dict:
      response = requests.post(
          f"https://api.stemfard.com/api/v1/mathematics/linear-algebra/matrix-operations/{endpoint}",
          headers={
              "Authorization": "Bearer <your-api-key>",
              "Content-Type": "application/json",
          },
          json=body,
      )

      if response.status_code == 401:
          raise PermissionError("Invalid or missing API key.")

      if response.status_code == 422:
          detail = response.json().get("detail", [])
          messages = ", ".join(
              f"{'.'.join(str(p) for p in d['loc'])}: {d['msg']}"
              for d in detail
          )
          raise ValueError(f"Validation error — {messages}")

      if response.status_code == 500:
          raise RuntimeError("Stemfard server error. Please try again later.")

      response.raise_for_status()
      return response.json()
  ```
</CodeGroup>

## Example error responses

**401 — missing API key**

```json theme={null}
{
  "detail": "Not authenticated"
}
```

**422 — missing required field**

```json theme={null}
{
  "detail": [
    {
      "loc": ["body", "a"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}
```

**422 — multiple validation failures**

```json theme={null}
{
  "detail": [
    {
      "loc": ["body", "a"],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": ["body", "operation"],
      "msg": "value is not a valid enumeration member; permitted: 'all', 'add', 'subtract', 'multiply-ew', 'divide-ew', 'raise-ew', 'matmul'",
      "type": "type_error.enum"
    }
  ]
}
```

<Warning>
  Do not retry requests that return `422`. A validation error means your request body is malformed — retrying the same request will always produce the same error. Fix the request body first, then retry.
</Warning>
