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

# Go SDK: migrating from v3 to v4

> Upgrade the Square Cloud Go SDK from v3 to v4: the /v4 import path, a snapshot Restore that reports a running restore, Metrics with a range and 409 RESTORE_IN_PROGRESS.

v4 is a breaking release because two signatures change. Snapshot `Restore` now tells you whether the restore is still running, and `Metrics` takes a range. Everything else is added on top: two new operations, for 69 in all, new fields and new error codes.

## At a glance

| | v3 | v4 |
| - | - | - |
| Module | `github.com/squarecloudofc/sdk-api-go/v3` | `github.com/squarecloudofc/sdk-api-go/v4` |
| Operations | 67 | 69, adding `Apps.Snapshots.RestoreState` and `Databases.Snapshots.RestoreState` |
| Snapshot restore | `Restore(ctx, id, name, versionID) error`. A restore still running after about 90 seconds returned `nil`, as if it had finished | `Restore(ctx, id, name, versionID) (SnapshotRestored, error)`. `Pending` is `true` while the restore keeps running, and `RestoreState` follows it |
| Metrics | `Metrics(ctx, id)`, for the last 24 hours only | `Metrics(ctx, id, rng)`, where `rng` is `""` or `"24h"`, or `"7d"` for hourly points with peaks |
| `RESTORE_IN_PROGRESS` | HTTP 403 | HTTP 409 |
| `CodeMetricsNotSupported` | Sent by the API | Deprecated: the API no longer sends it |
| Go version and dependencies | Go 1.22, no dependencies | Unchanged |

## Import path

Only the import path changes. `New` and every `Option` keep their signatures and defaults, and the default `User-Agent` becomes `squarecloud-sdk-go/4.0.0`.

```diff theme={"system"}
-import "github.com/squarecloudofc/sdk-api-go/v3"
+import "github.com/squarecloudofc/sdk-api-go/v4"
```

```bash theme={"system"}
go get github.com/squarecloudofc/sdk-api-go/v4@v4.0.0
```

## Breaking changes

The samples below run inside a function that returns an `error`.

### Snapshot restore

`Apps.Snapshots.Restore` and `Databases.Snapshots.Restore` return `(SnapshotRestored, error)` instead of `error`. A restore that takes longer than about 90 seconds keeps running after the call returns. v3 returned `nil` for it, so callers reported "restored" while it was still running. v4 returns `Pending: true` for it, and `Pending: false` for a finished restore.

```go theme={"system"}
// v3
if err := c.Apps.Snapshots.Restore(ctx, appID, snap.Name, snap.VersionID); err != nil {
	return err
}

// v4
res, err := c.Apps.Snapshots.Restore(ctx, appID, snap.Name, snap.VersionID)
if err != nil {
	return err
}
for res.Pending { // still running: follow it, never send the restore again
	time.Sleep(10 * time.Second)
	st, err := c.Apps.Snapshots.RestoreState(ctx, appID)
	if err != nil {
		return err
	}
	if st.State == "error" {
		return fmt.Errorf("restore failed: %s", st.Code)
	}
	res.Pending = st.State == "queued" || st.State == "running"
}
```

`RestoreState` reports `queued` or `running` while the restore runs, with the current `Step`, then `success` or `error`, with a `Code`, for 1 hour after it ends. It reports `none` after that hour or when there was no recent restore. It allows 30 calls a minute. See [Snapshots](https://docs.squarecloud.app/en/sdks/go/snapshots.md#following-a-restore).

### Metrics

`Apps.Metrics` and `Databases.Metrics` take a range as their last argument. Pass `""` to keep the v3 behavior, which covers the last 24 hours.

```go theme={"system"}
// v3
points, err := c.Apps.Metrics(ctx, appID)

// v4
points, err := c.Apps.Metrics(ctx, appID, "") // "" or "24h": the last 24 hours
```

`"7d"` returns hourly points with the hour's average and its `CPUMax` and `RAMMax` peaks, on the Pro and Enterprise plans for apps of 512 MB or more. Other plans and smaller apps get the 24-hour answer without an error, so check the points instead of assuming 7 days. Any other range returns 400 `INVALID_PARAMETERS`. For databases, `"7d"` needs a Pro or Enterprise plan. See [Metrics](https://docs.squarecloud.app/en/sdks/go/managing_application.md#metrics).

### `RESTORE_IN_PROGRESS` is 409

`RESTORE_IN_PROGRESS` moved from 403 to 409 on app and database delete and on database start and stop. It is also new, as 409, on app start, stop and restart and on snapshot `Create` and `Restore`. Match the code alone:

```go theme={"system"}
var apiErr *squarecloud.APIError

// v3
if errors.As(err, &apiErr) && apiErr.Status == 403 && apiErr.Code == squarecloud.CodeRestoreInProgress {
	// a snapshot restore is running
}

// v4
if errors.As(err, &apiErr) && apiErr.Code == squarecloud.CodeRestoreInProgress {
	// a snapshot restore is running (HTTP 409)
}
```

## New types and fields

| Type | New in v4 |
| - | - |
| `SnapshotRestored` | New: `Pending bool`, returned by `Restore` |
| `SnapshotRestoreState` | New: `State`, `Step` and `Code` (`string`), `StartedAt` and `FinishedAt` (`*int64`, Unix ms), returned by `RestoreState` |
| `ServiceStatus` | `Incidents []ServiceIncident`, the open incidents and maintenance windows, and `Components []ServiceComponent`, the parts of the platform that are not fully working. `Status` can be `"maintenance"`, and `"unknown"` means that the check could not run |
| `MetricPoint` | `Disk []int64`, the bytes read and written since the last start, and `Storage *int64`, the bytes on disk, both `nil` on a point without a reading. `CPUMax` and `RAMMax *float64`, the hourly peaks, set only with `"7d"` |
| `RuntimeStats`, `RuntimeStatsRaw` | `Restoring bool` |
| `DNSRecord` | `Errors []string`, up to 3 messages that say why a record is not active yet, and `Fallback bool`, which marks the one `_acme-challenge` CNAME that can replace every SSL TXT record |
| `AnalyticsTimeBucket` | `BytesIn int64` |
| `ChatRequest` | `MaxCompletionTokens int`, which wins over `MaxTokens` |

The new fields break only struct literals of these types that leave out the field names. Use field names.

## Errors

* New constants: `CodeAIWeeklyLimitReached`, `CodeEnvBusy` (409), `CodeGitBranchDeleted` and `CodeGitRefNotSupported` (sent only to GitHub push webhooks), `CodeRestoreInterrupted`, `CodeSnapshotsUnavailable` (503), `CodeSnapshotCorrupt`, `CodeSnapshotInProgress` (409), `CodeSnapshotRestoreProcessing` (reported as `SnapshotRestored.Pending`, never as an error), `CodeWriteFailed`, and `CodeWrongHost` (421, never returned to the calls of this SDK).
* `CodeMetricsNotSupported` is deprecated but kept.
* A restore can fail with more codes than `SNAPSHOT_RESTORE_FAILED`. See [Snapshots](https://docs.squarecloud.app/en/sdks/go/snapshots.md#restoring-a-snapshot) for the full list.
* The SDK retries none of the new codes. `SNAPSHOTS_UNAVAILABLE` asks you to wait about 30 seconds and `CLUSTER_MAINTENANCE_TRY_LATER` lasts minutes, both longer than the retry waits. A 409 from a busy resource is yours to decide.
* The SDK's own errors, `INVALID_API_KEY`, `INVALID_ID` and `FILE_TOO_LARGE`, have new messages that say what went wrong and how to fix it. Compare `Code`, not `Message`.

See [Errors](https://docs.squarecloud.app/en/sdks/go/errors.md) for the full reference.

## Behavior changes

* **Snapshot links expire after 1 hour.** They used to last 30 days, so download right after listing or creating a snapshot. Only `Create` can return an empty `URL` and `Key`, with `Pending: false`, when the API key lacks `snapshots:read`.
* **Snapshot listings** (`Account.Snapshots`, `Apps.Snapshots.List` and `Databases.Snapshots.List`) return 503 `SNAPSHOTS_UNAVAILABLE` instead of an empty list when snapshot storage cannot answer.
* **Metrics.** Apps below 512 MB now have metrics, with one point every 10 minutes, where they used to get 400 `METRICS_NOT_SUPPORTED`.
* **Environment variables.** `Envs.Set`, `Envs.Replace` and `Envs.Delete` return 409 `ENV_BUSY` when another write is in progress. With an API key that lacks `envs:read`, `Envs.Set` returns only the variables you sent, not the full set, and `Envs.Delete` returns an empty set.
* **Files.** `Files.Read` and `Files.Write` can return 400 `READ_FAILED` and `WRITE_FAILED`, and `Commit` can return 403 `BLOCKED_PATH`.
* **Parallel uploads.** The API limits how many large uploads an account can send at the same time. Going over the limit returns 429 `RATE_LIMITED`, which the SDK never retries.
* **AI.** A 429 from `AI.Chat` can be `weekly_limit_reached`.
* **User-Agent** is `squarecloud-sdk-go/4.0.0`.

## Checklist

**1. Change the import path**

Import `github.com/squarecloudofc/sdk-api-go/v4` everywhere and run `go get github.com/squarecloudofc/sdk-api-go/v4@v4.0.0`.

**2. Follow pending restores**

Replace `err := c.Apps.Snapshots.Restore(...)` with `res, err := ...`. When `res.Pending` is `true`, poll `RestoreState`, for example every 10 seconds, until `State` is `success` or `error`. Never send the restore again.

**3. Pass a range to Metrics**

Add `""`, `"24h"` or `"7d"` as the last argument of `Apps.Metrics` and `Databases.Metrics`.

**4. Match 409 RESTORE\_IN\_PROGRESS**

Match `409` where you matched `403`, or match the code alone.

**5. Handle 503 SNAPSHOTS\_UNAVAILABLE**

Handle it on snapshot listings, instead of reading an empty list as "no snapshots".

**6. Compare codes, not messages**

Check `Code` wherever you compared the `Message` of `INVALID_API_KEY`, `INVALID_ID` or `FILE_TOO_LARGE`.

## Next steps

> [card] [Client](https://docs.squarecloud.app/en/sdks/go/client.md)
>
> Install the SDK and create a client.

> [card] [Snapshots](https://docs.squarecloud.app/en/sdks/go/snapshots.md)
>
> Create, restore and follow snapshots.

> [card] [Errors](https://docs.squarecloud.app/en/sdks/go/errors.md)
>
> Error class, retries and rate limits.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.