> This page is for API.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.spreadspace.app/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.spreadspace.app/_mcp/server.

# Finalize the sample spread

POST https://api.spreadspace.app/api/sandbox/loans/{loan_id}/finalize
Content-Type: application/json

Exists for `ss_test_` keys only: finalizes the sandbox loan's sample spread through the same operation the workspace's Finalize runs, so the snapshot, the lock and the `spread.finalized` event are what a live finalize produces, with `livemode: false` the only difference. Needs `spreads:write`. The optional `external_user_id` lands in the snapshot's `finalized_by_external_user_id`. Answers 404 when the loan is not in the sandbox, 409 `spread_already_finalized` until a reopen, and 409 `spread_not_ready` when no sample document has completed on the loan; the sample spread is built from the `tax-1065-2024` sample. A live key gets 403 `mode_mismatch`. Honors `Idempotency-Key`: a replay returns the same `snapshot_id` and `event_id` and queues nothing.

Requires the `spreads:write` scope. Rate limit: 10 requests per minute per key (the `strict` lane).

Reference: https://docs.spreadspace.app/api/api-reference/sandbox/finalize-spread

## Authentication

- `Authorization` header (bearer token, required) — Bearer token. Use `ss_live_…` for live data or `ss_test_…` for the sandbox (test mode). See [Authentication](https://docs.spreadspace.app/api/authentication).

## Request

### Path parameters

- `loan_id` (string, required)

### Headers

- `Idempotency-Key` (string, optional) — Idempotency token. Retries that reuse the key within 24h replay the original response. Up to 255 characters; a UUID is typical. See [Idempotency](https://docs.spreadspace.app/api/idempotency).
- `SpreadSpace-Version` (string, optional) — Pin the API version, e.g. `2026-10-07`. Omit to get the latest. See [Versioning](https://docs.spreadspace.app/api/versioning).

### Body (application/json)

This endpoint expects a FinalizeSandboxSpreadRequest.

- `external_user_id` (string, optional, nullable) — Opaque id of your own end user, 1 to 256 characters once trimmed. Lands in the snapshot's `finalized_by_external_user_id`, exactly as an embed session's finalize would stamp it. Omit it and the field reads null.

## Response

### 200

OK

- `loan_id` (string, required)
- `borrower_id` (string, required)
- `spread_board_id` (string, required)
- `snapshot_id` (string, required) — The `final` snapshot this finalize minted.
- `machine_snapshot_id` (string, required) — The documents-only `machine` snapshot minted beside it.
- `version` (integer, required)
- `finalized_at` (datetime, required)
- `event_id` (string, required) — The id of the `spread.finalized` event this finalize queued; the delivery's `id` and `SpreadSpace-Event-Id` equal it.

## Errors

### 400 Bad Request Error

Bad request: validation failed, the cursor is malformed, or the API version is unknown.

- `error` (ApiErrorBody, required) — Inner body of the canonical API error envelope.

### 401 Unauthorized Error

Unauthorized: the bearer token or API key is missing or invalid.

- `error` (ApiErrorBody, required) — Inner body of the canonical API error envelope.

### 403 Forbidden Error

Forbidden: authentication succeeded but the caller is not permitted to perform this action, for example an API key missing the required scope, an embed session reaching a loan it was not minted for, or a feature outside the workspace's plan.

- `error` (ApiErrorBody, required) — Inner body of the canonical API error envelope.

### 404 Not Found Error

Not Found

- `any`

### 409 Conflict Error

Conflict: a version mismatch, where `details.current_version` carries the version the resource is actually at so the client can reload and re-apply, or an idempotency key reused with a different request body.

- `error` (ApiErrorBody, required) — Inner body of the canonical API error envelope.

### 429 Too Many Requests Error

Too many requests: the rate limit was hit, or an idempotency-key replay is still in progress.

- `error` (ApiErrorBody, required) — Inner body of the canonical API error envelope.

### 500 Internal Server Error

Internal server error: an unexpected failure. Quote the `request_id` in support tickets. A mutation sent with an `Idempotency-Key` replays this fault under that key rather than re-running; confirm the resource state before resending with a new key.

- `error` (ApiErrorBody, required) — Inner body of the canonical API error envelope.

## Types

### ApiErrorBody

Inner body of the canonical API error envelope.

- `type` (enum, required) — Stable error type identifier, one of the values listed. Pattern-match on this value, not the human-readable message. A later version may add a value; treat one you do not know by its HTTP status.
  - Allowed values: `billing_required`, `business_email_required`, `conflict`, `counterparty_not_in_plan`, `cursor_expired`, `custom_visual_limit_exceeded`, `doc_too_large`, `embed_not_in_plan`, `embed_origin_not_allowed`, `embed_scope_exceeds_key`, `embed_scope_not_allowed`, `embed_session_binding_mismatch`, `embed_session_not_found`, `embed_token_expired`, `forbidden`, `geometry_plan_denied`, `html_upload_disabled`, `idempotency_in_progress`, `idempotency_request_mismatch`, `idempotency_response_too_large`, `insufficient_credits`, `insufficient_scope`, `internal_error`, `invalid_code`, `invalid_cursor`, `invalid_embed_token`, `invalid_include`, `invalid_limit`, `invalid_request`, `invalid_session_handle`, `invalid_version`, `key_expired`, `key_revoked`, `last_item`, `license_assigned`, `license_holder_has_license`, `license_none_free`, `license_reassign_window`, `licenses_assigned`, `markets_api_required`, `memo_locked`, `memo_not_locked`, `mfa_enrollment_required`, `mode_mismatch`, `not_found`, `payload_too_large`, `payment_failed`, `pii_claim_required`, `rate_limited`, `render_failed`, `request_cancelled`, `research_not_in_plan`, `resource_gone`, `same_origin_required`, `sandbox_missing`, `sandbox_organization`, `scope_not_in_product`, `scope_state_changed`, `session_handle_already_used`, `session_handle_expired`, `session_handle_revoked`, `spend_cap_reached`, `spread_already_finalized`, `spread_limit`, `spread_locked`, `spread_not_finalized`, `spread_not_locked`, `spread_not_ready`, `spread_template_limit_exceeded`, `spreads_not_in_plan`, `spreadsheet_upload_disabled`, `statement_mapping_not_in_plan`, `subscription_required`, `surface_limit_exceeded`, `test_key_remint_required`, `unauthorized`, `unknown_factor`, `unprocessable`, `usage_throttled`, `validation_failed`
- `message` (string, required) — Human-readable error message. Subject to wording changes; do not parse.
- `code` (string, optional) — A finer, stable identifier within `type`, on the errors that carry one; absent otherwise. Pattern-match on it like `type`. The upload presign answers `not_found` with `loan_not_found` and `invalid_request` with `borrower_loan_mismatch`.
- `request_id` (string, optional, nullable) — Per-request correlation ID (matches `X-Request-ID` response header). Quote in support tickets.
- `details` (map from string to string, optional, nullable) — Structured detail. Some error types populate documented keys in every environment: a version conflict (409) carries `current_version`, the version the resource is actually at, so the client can reload and re-apply. Free-form diagnostic detail beyond those keys appears in development environments only. An `insufficient_credits` 402 carries `balance_usd`, `reserved_usd`, `in_flight_docs`, `incoming_docs` and `per_doc_reservation_usd` as decimal strings.

## Examples

**Request**

```json
{
  "external_user_id": "user-4821"
}
```

**Response**

```json
{
  "loan_id": "8f3b2c1d4e5f678901234567",
  "borrower_id": "9f8e7d6c5b4a3210a1b2c3d4",
  "spread_board_id": "0c9d8e7f6a5b4c3d2e1f0a9b",
  "snapshot_id": "8a7b6c5d4e3f2a1b0c9d8e7f",
  "machine_snapshot_id": "2d4f6a8c0e1b3d5f7a9c1e3b",
  "version": 2,
  "finalized_at": "2024-04-10T14:45:02.684432+00:00",
  "event_id": "evt_7d3e1f9a2b4c5d6e8f0a1b2c"
}
```

**SDK Code**

```typescript
import { SpreadSpace } from '@spreadspace/sdk';

const client = new SpreadSpace({ apiKey: process.env.SPREADSPACE_API_KEY! });

const finalized = await client.sandbox.finalizeSpread({ loanId: '8f3b2c1d4e5f678901234567', externalUserId: 'user-4821' });
console.log(finalized.snapshot_id, finalized.event_id);

```

```python
import os

from spreadspace import SpreadSpace

client = SpreadSpace(api_key=os.environ["SPREADSPACE_API_KEY"])

finalized = client.sandbox.finalize_spread(loan_id="8f3b2c1d4e5f678901234567", external_user_id="user-4821")
print(finalized["snapshot_id"], finalized["event_id"])

```

```csharp
using SpreadSpace;

using var client = new SpreadSpaceClient(Environment.GetEnvironmentVariable("SPREADSPACE_API_KEY"));

var finalized = await client.Sandbox.FinalizeSpreadAsync("8f3b2c1d4e5f678901234567", externalUserId: "user-4821");
Console.WriteLine($"{finalized.SnapshotId} {finalized.EventId}");

```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.spreadspace.app/api/sandbox/loans/8f3b2c1d4e5f678901234567/finalize"

	payload := strings.NewReader("{\n  \"external_user_id\": \"user-4821\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.spreadspace.app/api/sandbox/loans/8f3b2c1d4e5f678901234567/finalize")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"external_user_id\": \"user-4821\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.spreadspace.app/api/sandbox/loans/8f3b2c1d4e5f678901234567/finalize")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"external_user_id\": \"user-4821\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.spreadspace.app/api/sandbox/loans/8f3b2c1d4e5f678901234567/finalize', [
  'body' => '{
  "external_user_id": "user-4821"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["external_user_id": "user-4821"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.spreadspace.app/api/sandbox/loans/8f3b2c1d4e5f678901234567/finalize")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```