# hanamii Public API Reference

Last updated: 2026-10-29

This Markdown file is optimized for AI agents and code generation. It describes the hanamii Public API using English section names, endpoint paths, field names, request examples, response examples, and error contracts. Japanese text appears only where the API actually returns Japanese messages.

## Conventions

- Base URL: `https://hanamii.jp`
- All endpoints are under `/api/v1`.
- Authentication: `Authorization: Bearer <API_TOKEN>`.
- JSON mutation endpoints require `Content-Type: application/json`.
- ZIP uploads use a temporary signed ZIP-upload URL flow (`/api/v1/uploads`, separate from Object Storage): create upload URL, PUT the ZIP to that URL, create a `checkId`, then deploy with that `checkId`.
- Timestamps are Unix epoch milliseconds unless otherwise noted.
- API token strings start with `hnm_`.

```bash
export BASE_URL="https://hanamii.jp"
export HANAMII_TOKEN="hnm_..."
```

## Authentication

All requests require a Bearer token.

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/user/tokens"
```

Authentication failures return `401 unauthorized`. The message is intentionally generic.

```json
{
  "error": {
    "code": "unauthorized",
    "message": "認証に失敗しました"
  }
}
```

## Pagination

List endpoints support cursor pagination.

| Name | Type | Required | Description |
|---|---|---|---|
| `limit` | number | no | Number of items to return. Default `20`, maximum `100`. |
| `until` | number | no | Pass the previous response's `pagination.next` value to fetch the next page. |
| `since` | number | no | Pass the previous response's `pagination.prev` value to fetch the previous direction. |

Example:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects?limit=20"
```

Pagination response:

```json
{
  "pagination": {
    "count": 20,
    "next": 1777622400000,
    "prev": 1777626000000
  }
}
```

If `pagination.next` is `null`, there is no next page.

## Workspace Scope and Role

API tokens have a scope.

| Scope | Description |
|---|---|
| `full_account` | The token can target workspaces that the token owner belongs to. |
| `workspace` | The token can target only the specified workspace. |

Even with `full_account`, each operation is constrained by the user's role in the target workspace.

| Operation | owner | admin | developer | viewer |
|---|---|---|---|---|
| List/retrieve projects | yes | yes | yes | yes |
| List project logs | yes | yes | yes | yes |
| List environment variables | yes | yes | yes | no |
| Create projects / deploy / redeploy | yes | yes | yes | no |
| Upsert environment variables | yes | yes | yes | no |
| Delete projects | yes | yes | no | no |
| Retrieve project database | yes | yes | yes | yes |
| Manage project database (create/delete, connection tokens, data read, export, import) | yes | yes | no | no |
| List Storage buckets/files, issue viewing URLs, retrieve usage | yes | yes | yes | yes |
| Create/delete Storage buckets, manage bucket keys | yes | yes | no | no |

Use `GET /api/v1/workspaces` to discover accessible `workspaceId` values.

## Endpoint Summary

| Method | Path | Description |
|---|---|---|
| GET | `/api/v1/workspaces/:workspaceId/storage/buckets` | List Storage buckets and discover the file API origin. |
| POST | `/api/v1/workspaces/:workspaceId/storage/buckets` | Create a Storage bucket (owner/admin). |
| DELETE | `/api/v1/workspaces/:workspaceId/storage/buckets/:bucketId` | Delete a Storage bucket (owner/admin). |
| GET | `/api/v1/workspaces/:workspaceId/storage/buckets/:bucketId/access-keys` | List key metadata (owner/admin; no plaintext). |
| POST | `/api/v1/workspaces/:workspaceId/storage/buckets/:bucketId/access-keys` | Issue a bucket key (owner/admin; plaintext returned once). |
| DELETE | `/api/v1/workspaces/:workspaceId/storage/buckets/:bucketId/access-keys/:keyId` | Revoke a bucket key (owner/admin). |
| GET | `/api/v1/workspaces/:workspaceId/storage/buckets/:bucketId/files` | List file metadata (all members). |
| POST | `/api/v1/workspaces/:workspaceId/storage/buckets/:bucketId/files/:fileId/view-url` | Issue a viewing URL (all members). |
| GET | `/api/v1/workspaces/:workspaceId/storage/usage` | Retrieve workspace usage and limits (all members). |
| GET | `/api/v1/user/tokens` | List active API tokens. |
| POST | `/api/v1/user/tokens` | Create an API token. |
| GET | `/api/v1/user/tokens/:id` | Retrieve API token metadata. |
| DELETE | `/api/v1/user/tokens/:id` | Revoke an API token. |
| GET | `/api/v1/workspaces` | List accessible workspaces. |
| GET | `/api/v1/projects` | List accessible projects. |
| POST | `/api/v1/projects` | Create a project and start the first deployment. |
| GET | `/api/v1/projects/:id` | Retrieve a project. |
| DELETE | `/api/v1/projects/:id` | Delete a project. |
| POST | `/api/v1/projects/:id/deploy` | Start a redeployment. |
| GET | `/api/v1/projects/:id/logs` | List project runtime logs. |
| GET | `/api/v1/projects/:id/env` | List project environment variables. |
| PATCH | `/api/v1/projects/:id/env` | Upsert project environment variables. |
| GET | `/api/v1/projects/:id/health-check` | Retrieve the health check setting. |
| PUT | `/api/v1/projects/:id/health-check` | Save the health check setting. |
| POST | `/api/v1/projects/:id/restart` | Apply saved settings to the running app. |
| GET | `/api/v1/projects/:id/database` | Retrieve the project database. |
| POST | `/api/v1/projects/:id/database` | Create an empty project database. |
| DELETE | `/api/v1/projects/:id/database` | Delete the project database. |
| GET | `/api/v1/projects/:id/database/auth-tokens` | List database connection tokens. |
| POST | `/api/v1/projects/:id/database/auth-tokens` | Issue a database connection token. |
| DELETE | `/api/v1/projects/:id/database/auth-tokens/:tokenId` | Revoke a database connection token. |
| GET | `/api/v1/projects/:id/database/tables` | List tables and columns (read-only). |
| GET | `/api/v1/projects/:id/database/tables/:table/rows` | Read rows of a table (read-only, paginated). |
| POST | `/api/v1/projects/:id/database/exports` | Start an export to a SQLite file. |
| GET | `/api/v1/projects/:id/database/exports/:exportJobId` | Retrieve export job status. |
| POST | `/api/v1/projects/:id/database/exports/:exportJobId/download` | Issue a download URL for a finished export. |
| POST | `/api/v1/projects/:id/database/import-session` | Create signed upload URLs for a SQLite file import. |
| POST | `/api/v1/projects/:id/database/import-start` | Start creating the database from the uploaded file. |

## API Tokens

### GET /api/v1/user/tokens

Description:
List active API tokens for the authenticated user.

Authentication:
Bearer token required.

Query parameters:

| Name | Type | Required | Description |
|---|---|---|---|
| `limit` | number | no | Default `20`, maximum `100`. |
| `until` | number | no | Cursor from `pagination.next`. |
| `since` | number | no | Cursor from `pagination.prev`. |

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/user/tokens?limit=20"
```

Response `200`:

```json
{
  "tokens": [
    {
      "id": "tok_123",
      "name": "GitHub Actions Deploy",
      "scopeType": "workspace",
      "scopeWorkspaceId": "ws_123",
      "createdAt": 1777622400000,
      "expiresAt": null,
      "lastUsedAt": null
    }
  ],
  "pagination": {
    "count": 1,
    "next": null,
    "prev": 1777622400000
  }
}
```

Notes:
List and retrieve endpoints never return `bearerToken` or `tokenHash`.

### POST /api/v1/user/tokens

Description:
Create an API token. The plaintext token is returned only once in `bearerToken`.

Authentication:
Bearer token required.

Headers:

| Name | Required | Value |
|---|---|---|
| `Content-Type` | yes | `application/json` |

Request body:

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | string | yes | Display label for the token. |
| `scopeType` | string | yes | `full_account` or `workspace`. |
| `scopeWorkspaceId` | string or null | conditional | Required when `scopeType` is `workspace`; null for `full_account`. |
| `expiresAt` | number or null | no | Unix epoch milliseconds. `null` means no expiration. Maximum is one year from creation. |

Request:

```bash
curl -X POST "$BASE_URL/api/v1/user/tokens" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "name": "GitHub Actions Deploy",
    "scopeType": "workspace",
    "scopeWorkspaceId": "ws_123",
    "expiresAt": null
  }'
```

Response `200`:

```json
{
  "token": {
    "id": "tok_123",
    "name": "GitHub Actions Deploy",
    "scopeType": "workspace",
    "scopeWorkspaceId": "ws_123",
    "createdAt": 1777622400000,
    "expiresAt": null,
    "lastUsedAt": null
  },
  "bearerToken": "hnm_plaintext_token"
}
```

### GET /api/v1/user/tokens/:id

Description:
Retrieve API token metadata. Use `current` as `:id` to retrieve the token used to authenticate the current request.

Authentication:
Bearer token required.

Path parameters:

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Token ID or `current`. |

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/user/tokens/current"
```

Response `200`:

```json
{
  "token": {
    "id": "tok_123",
    "name": "GitHub Actions Deploy",
    "scopeType": "workspace",
    "scopeWorkspaceId": "ws_123",
    "createdAt": 1777622400000,
    "expiresAt": null,
    "lastUsedAt": 1777622500000
  }
}
```

### DELETE /api/v1/user/tokens/:id

Description:
Revoke an API token. Use `current` as `:id` to revoke the token used to authenticate the current request.

Authentication:
Bearer token required.

Path parameters:

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Token ID or `current`. |

Request:

```bash
curl -X DELETE "$BASE_URL/api/v1/user/tokens/current" \
  -H "Authorization: Bearer $HANAMII_TOKEN"
```

Response `200`:

```json
{
  "token": {
    "id": "tok_123",
    "deleted": true
  }
}
```

After revocation, the same token returns `401 unauthorized`.

## Workspaces

### GET /api/v1/workspaces

Description:
List workspaces accessible by the authenticated API token.

Authentication:
Bearer token required.

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/workspaces"
```

Response `200`:

```json
{
  "workspaces": [
    {
      "id": "ws_123",
      "name": "Main Workspace",
      "role": "owner"
    }
  ]
}
```

Rules:
`full_account` tokens return workspaces that the token owner belongs to. `workspace` scope tokens return only the scoped workspace.

## Projects

### GET /api/v1/projects

Description:
List projects accessible by the authenticated API token.

Authentication:
Bearer token required.

Query parameters:

| Name | Type | Required | Description |
|---|---|---|---|
| `workspaceId` | string | no | Filter projects by workspace. |
| `limit` | number | no | Default `20`, maximum `100`. |
| `until` | number | no | Cursor from `pagination.next`. |
| `since` | number | no | Cursor from `pagination.prev`. |

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects?workspaceId=ws_123&limit=20"
```

Rules:
If `workspaceId` is omitted, the response includes projects from all workspaces visible to the token.

Response `200`:

```json
{
  "projects": [
    {
      "id": "prj_123",
      "name": "my-app",
      "status": "healthy",
      "workspaceId": "ws_123",
      "url": "https://app-xxxx.ingress.apprun.sakura.ne.jp",
      "urls": [
        {
          "type": "default",
          "host": "app-xxxx.ingress.apprun.sakura.ne.jp",
          "url": "https://app-xxxx.ingress.apprun.sakura.ne.jp"
        },
        {
          "type": "custom",
          "host": "example.com",
          "url": "https://example.com"
        }
      ],
      "latestDeployment": {
        "id": "dep_123",
        "readyState": "READY",
        "errorCode": null
      },
      "runtimeStatus": {
        "status": "healthy",
        "detail": null,
        "syncedAt": 1777622400000
      },
      "healthCheck": {
        "enabled": true,
        "path": "/health",
        "port": null
      },
      "createdAt": 1777622400000,
      "updatedAt": 1777622400000
    }
  ],
  "pagination": {
    "count": 1,
    "next": null,
    "prev": 1777622400000
  }
}
```

### POST /api/v1/projects

Description:
Create a project and start the first deployment. For ZIP source, first use the upload flow to create a `checkId`, then pass that `checkId` in the project creation request.

For ZIP source, exclude files such as `node_modules`, `vendor`, `.git`, `.env*`, `.next`, `dist`, `build`, and caches before creating the ZIP. hanamii also removes unnecessary directories during check, but larger source ZIPs take longer to process. For regular CI/CD, Git deploy is recommended.

`envs` and `healthCheck` are optional for both Git and ZIP project creation. If omitted, the project is created without those settings.

Authentication:
Bearer token required.

JSON request body for Git source:

| Name | Type | Required | Description |
|---|---|---|---|
| `workspaceId` | string | conditional | Required for `full_account` tokens. Ignored/forced for `workspace` scope tokens. |
| `name` | string | yes | Project name. Lowercase letters, digits, and hyphens. |
| `source.type` | string | yes | `git`. |
| `source.repoFullName` | string | yes | GitHub repository full name, e.g. `owner/repo`. |
| `source.ref` | string | yes | Branch or ref. |
| `source.rootDirectory` | string | no | Root directory. |
| `envs` | array | no | Environment variables to save and apply during the first deployment. |
| `healthCheck.enabled` | boolean | no | Enable AppRun HTTP health check. |
| `healthCheck.path` | string | conditional | Required when `healthCheck.enabled=true`. Must start with `/`. |
| `healthCheck.port` | number \| null | no | `null` or omitted uses the AppRun application port. |

Git request:

```bash
# envs and healthCheck are optional. Omit them if you do not need them.
curl -X POST "$BASE_URL/api/v1/projects" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "workspaceId": "ws_123",
    "name": "my-git-app",
    "source": {
      "type": "git",
      "repoFullName": "owner/repo",
      "ref": "main",
      "rootDirectory": "."
    },
    "envs": [
      { "key": "API_URL", "value": "https://example.com", "type": "plain" }
    ],
    "healthCheck": {
      "enabled": true,
      "path": "/health",
      "port": null
    }
  }'
```

ZIP upload flow:

Note: When using cURL for ZIP check or deploy, use `-N` so streamed keepalive whitespace is delivered while the server is still working.
Each `checkId` is single-use. Create a new upload and check result for every deploy or redeploy. Reusing a consumed `checkId` returns `400 validation_error`.

```bash
# 1. Create uploadUrl and uploadId.
curl -s -X POST "$BASE_URL/api/v1/uploads" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "workspaceId": "ws_123",
    "fileName": "frontend.zip",
    "contentType": "application/zip"
  }'

# Response:
# {
#   "upload": {
#     "id": "upload_123",
#     "uploadUrl": "https://object-storage.example.com/...",
#     "putCurl": "curl -X PUT 'https://object-storage.example.com/...' -H 'Content-Type: application/zip' --data-binary '@/path/to/frontend.zip'",
#     "expiresAt": 1777622700000
#   }
# }

# 2. Copy upload.putCurl, change only the required values, and run it.
curl -X PUT 'https://object-storage.example.com/...' -H 'Content-Type: application/zip' --data-binary '@/path/to/frontend.zip'

# 3. Paste upload.id into the path, validate the uploaded ZIP, and create checkId.
curl -sS -N -X POST "$BASE_URL/api/v1/uploads/upload_123/check" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{}'

# Response:
# {
#   "result": {
#     "checkId": "check_123",
#     "canDeploy": true,
#     "errorCount": 0,
#     "errors": []
#   }
# }

# 4. Paste result.checkId into source.checkId and create the project.
# envs and healthCheck are optional. Omit them if you do not need them.
curl -N -X POST "$BASE_URL/api/v1/projects" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "workspaceId": "ws_123",
    "name": "my-zip-app",
    "source": {
      "type": "zip",
      "checkId": "check_123"
    },
    "envs": [
      { "key": "API_URL", "value": "https://example.com", "type": "plain" }
    ],
    "healthCheck": {
      "enabled": true,
      "path": "/health",
      "port": null
    }
  }'
```

Reused `checkId` response:

```json
{
  "error": {
    "code": "validation_error",
    "message": "ZIPファイルが見つかりません。再度チェックを実行してください"
  }
}
```

Response `200`:

```json
{
  "project": {
    "id": "prj_123",
    "name": "my-app",
    "workspaceId": "ws_123",
    "status": "initial",
    "createdAt": 1777622400000,
    "updatedAt": 1777622400000
  },
  "deployment": {
    "id": "dep_123",
    "readyState": "BUILDING",
    "errorCode": null
  }
}
```

Project creation is a start API. The `project` object in this response does not include `url`, `urls`, `latestDeployment`, or `healthCheck`. Poll `GET /api/v1/projects/:id` after deployment starts to read URLs and deployment state. Use `GET /api/v1/projects/:id/health-check` to read the saved health check setting.
Reserved AppRun ports `8012`, `8013`, `8022`, `9090`, `9091`, and `8008` are rejected for `healthCheck.port`.

### GET /api/v1/projects/:id

Description:
Retrieve a project.

Authentication:
Bearer token required.

Path parameters:

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Project ID. |

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123"
```

Response `200`:

```json
{
  "project": {
    "id": "prj_123",
    "name": "my-app",
    "status": "healthy",
    "workspaceId": "ws_123",
    "url": "https://app-xxxx.ingress.apprun.sakura.ne.jp",
    "urls": [
      {
        "type": "default",
        "host": "app-xxxx.ingress.apprun.sakura.ne.jp",
        "url": "https://app-xxxx.ingress.apprun.sakura.ne.jp"
      }
    ],
    "latestDeployment": {
      "id": "dep_123",
      "readyState": "READY",
      "errorCode": null
    },
    "runtimeStatus": {
      "status": "healthy",
      "detail": null,
      "syncedAt": 1777622400000
    },
    "healthCheck": {
      "enabled": true,
      "path": "/health",
      "port": null
    },
    "createdAt": 1777622400000,
    "updatedAt": 1777622400000
  }
}
```

Project URL and deployment polling rules:

- `project.url` is the primary URL to access the deployed app. A verified custom domain with issued SSL is preferred over the default AppRun URL.
- `project.urls` lists available URLs. The default URL is included when known. Custom domains are included only when verified and SSL is issued.
- `latestDeployment` is `null` if the project has no deployment yet.
- `latestDeployment` represents the most recent deployment attempt, not necessarily the deployment currently serving traffic.
- If a redeploy fails while a previous deployment is still healthy, `project.status` and `project.url` may still represent the currently running app, while `latestDeployment.readyState` is `ERROR`.
- `latestDeployment.readyState` is one of `QUEUED`, `BUILDING`, `READY`, or `ERROR`.
- Treat `latestDeployment.readyState === "ERROR"` as a failed deploy. `errorCode` is optional detail and may be `check_error`, `build_error`, `deploy_error`, `health_error`, or `null`.
- `errorMessage` and build logs are not included in project responses.
- `runtimeStatus` is the AppRun runtime snapshot and is separate from `project.status` and `latestDeployment.readyState`.
- `healthCheck.enabled=false` means no health check row is configured.




### POST /api/v1/projects/:id/deploy

Description:
Start a redeployment. For ZIP source, first use the upload flow to create a `checkId`, then pass that `checkId` in the redeploy request.

For ZIP source, exclude files such as `node_modules`, `vendor`, `.git`, `.env*`, `.next`, `dist`, `build`, and caches before creating the ZIP. hanamii also removes unnecessary directories during check, but larger source ZIPs take longer to process. For regular CI/CD, Git deploy is recommended.

Authentication:
Bearer token required.

Git redeploy request:

```bash
curl -X POST "$BASE_URL/api/v1/projects/prj_123/deploy" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "source": {
      "type": "git"
    }
  }'
```

ZIP redeploy flow:

Note: When using cURL for ZIP check or redeploy, use `-N` so streamed keepalive whitespace is delivered while the server is still working.
Each `checkId` is single-use. Run the upload and check flow again for every redeploy.

```bash
# 1. Create uploadUrl, putCurl, and upload.id.
curl -s -X POST "$BASE_URL/api/v1/uploads" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "workspaceId": "ws_123",
    "fileName": "frontend.zip",
    "contentType": "application/zip"
  }'

# 2. Copy upload.putCurl, change only the required values, and run it.
curl -X PUT 'https://object-storage.example.com/...' -H 'Content-Type: application/zip' --data-binary '@/path/to/frontend.zip'

# 3. Validate the uploaded ZIP and create checkId.
curl -sS -N -X POST "$BASE_URL/api/v1/uploads/upload_123/check" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{}'

# 4. Redeploy with result.checkId.
curl -N -X POST "$BASE_URL/api/v1/projects/prj_123/deploy" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "source": {
      "type": "zip",
      "checkId": "check_123"
    }
  }'
```

Response `200`:

```json
{
  "project": {
    "id": "prj_123",
    "name": "my-app",
    "status": "healthy",
    "workspaceId": "ws_123",
    "createdAt": 1777622400000,
    "updatedAt": 1777622400000
  },
  "deployment": {
    "id": "dep_123",
    "readyState": "BUILDING",
    "errorCode": null
  }
}
```

The redeploy response's top-level `project` is a summary of the existing project, and `deployment` is the deployment that was just started. Start API project responses do not include `url`, `urls`, or `latestDeployment`. Poll `GET /api/v1/projects/:id` and use `project.url` when `latestDeployment.readyState` becomes `READY`.



### DELETE /api/v1/projects/:id

Description:
Delete a project. If external resource deletion continues durably, the API returns `202` without claiming that the project has already been deleted.

Authentication:
Bearer token required.

Path parameters:

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | string | yes | Project ID. |

Request:

```bash
curl -X DELETE "$BASE_URL/api/v1/projects/prj_123" \
  -H "Authorization: Bearer $HANAMII_TOKEN"
```

Response `200`:

```json
{
  "project": {
    "id": "prj_123",
    "deleted": true,
    "deletion": "completed"
  }
}
```

Response `202`:

```json
{
  "project": {
    "id": "prj_123",
    "deleted": false,
    "deletion": "accepted",
    "operationId": "operation_123",
    "requiresReview": false
  }
}
```

## Project Logs

### GET /api/v1/projects/:id/logs

Description:
List project runtime logs.

Retention:
New logs are retained for 24 hours on the free plan or 90 days on a paid plan, based on the workspace plan when each log is stored. After a downgrade to the free plan, logs stored during the paid period keep their original 90-day expiry; newly stored logs are retained for 24 hours. Expired logs are excluded from results and deleted in due course. Changing plans does not restore logs that have already been deleted.

Request range:
If both `since` and `before` are omitted, the API queries the last 15 minutes. The retention period and the range of a single request are different.

Authentication:
Bearer token required.

Query parameters:

| Name | Type | Required | Description |
|---|---|---|---|
| `limit` | number | no | Default `100`, maximum `500`. This is a line count. |
| `since` | string | no | ISO 8601 datetime or relative value such as `-15m`, `-2h`, `-1d`. Defaults to `-15m`. |
| `before` | string | no | ISO 8601 datetime. Takes priority over `since`. |
| `format` | string | no | Set to `text` to return `text/plain`. |

JSON request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123/logs?limit=100&since=-15m"
```

Response `200`:

```json
{
  "logs": [
    {
      "timestamp": "2026-05-05T12:00:00.000Z",
      "message": "Server started"
    }
  ]
}
```

Text request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123/logs?limit=100&since=-15m&format=text"
```

Response `200` with `text/plain`:

```text
21:00:00 Server started
21:00:01 GET /health 200
```

Rules:
The API does not truncate or abbreviate `message` values.
If there are no matching runtime logs, `format=text` still returns `200` with an empty body and `Content-Type: text/plain; charset=utf-8`.

## Environment Variables

### GET /api/v1/projects/:id/env

Description:
List project environment variables. Saved environment variables are applied to the running app on the next redeploy or by calling `POST /api/v1/projects/:id/restart`.

Authentication:
Bearer token required.

Query parameters:

| Name | Type | Required | Description |
|---|---|---|---|
| `decrypt` | boolean | no | If `true`, include `value`. Otherwise secret values are omitted. |

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123/env"
```

Response `200`:

```json
{
  "envs": [
    {
      "key": "NODE_ENV",
      "type": "plain",
      "isSensitive": false,
      "createdAt": 1777622400000,
      "updatedAt": 1777622400000
    },
    {
      "key": "DATABASE_URL",
      "type": "secret",
      "isSensitive": true,
      "createdAt": 1777622400000,
      "updatedAt": 1777622400000
    }
  ]
}
```

Rules:
Default responses do not include `value`, `encryptedValue`, or `iv`.
`type` is always `secret` or `plain`; `encrypted` is not returned by the public API.

### PATCH /api/v1/projects/:id/env

Description:
Upsert project environment variables by key. This endpoint only saves settings. To apply saved environment variables to the running app, call `POST /api/v1/projects/:id/restart` or redeploy the project. Omitted existing keys are not deleted.

Authentication:
Bearer token required.

Headers:

| Name | Required | Value |
|---|---|---|
| `Content-Type` | yes | `application/json` |

Request body:

| Name | Type | Required | Description |
|---|---|---|---|
| `envs` | array | yes | Environment variable items. |
| `envs[].key` | string | yes | Environment variable key. |
| `envs[].value` | string | yes | Environment variable value. |
| `envs[].type` | string | no | `secret` or `plain`. Default `secret`. |

Request:

```bash
curl -X PATCH "$BASE_URL/api/v1/projects/prj_123/env" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "envs": [
      {
        "key": "NODE_ENV",
        "value": "production",
        "type": "plain"
      },
      {
        "key": "DATABASE_URL",
        "value": "postgres://user:pass@example.com:5432/app",
        "type": "secret"
      }
    ]
  }'
```

Response `200`:

```json
{
  "envs": [
    {
      "key": "NODE_ENV",
      "type": "plain",
      "isSensitive": false,
      "createdAt": 1777622400000,
      "updatedAt": 1777622400000
    },
    {
      "key": "DATABASE_URL",
      "type": "secret",
      "isSensitive": true,
      "createdAt": 1777622400000,
      "updatedAt": 1777622400000
    }
  ]
}
```


### GET /api/v1/projects/:id/health-check

Description:
Read the saved AppRun health check setting. Saved health check settings are applied to the running app on the next redeploy or by calling `POST /api/v1/projects/:id/restart`.

Authentication:
Bearer token required.

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123/health-check"
```

Response `200`:

```json
{
  "healthCheck": {
    "enabled": false,
    "path": null,
    "port": null
  }
}
```


### PUT /api/v1/projects/:id/health-check

Description:
Enable, update, or disable the AppRun health check setting. This endpoint only saves settings. To apply the saved health check to the running app, call `POST /api/v1/projects/:id/restart` or redeploy the project.

Authentication:
Bearer token required.

Headers:

| Name | Required | Value |
|---|---|---|
| `Content-Type` | yes | `application/json` |

Request body:

| Name | Type | Required | Description |
|---|---|---|---|
| `enabled` | boolean | yes | `true` saves a row, `false` deletes it. |
| `path` | string | conditional | Required when enabled. Must start with `/`. |
| `port` | number \| null | no | `null` or omitted uses the AppRun application port. |

Request:

```bash
curl -X PUT "$BASE_URL/api/v1/projects/prj_123/health-check" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "enabled": true,
    "path": "/health",
    "port": null
  }'
```

Response `200`:

```json
{
  "healthCheck": {
    "enabled": true,
    "path": "/health",
    "port": null
  }
}
```

Rules:
When `enabled=false`, `path` and `port` are ignored and the saved row is deleted. Reserved AppRun ports `8012`, `8013`, `8022`, `9090`, `9091`, and `8008` return `400 validation_error`.

The saved health check is used during deploy and restart. hanamii sends the check to the saved path and port. If the path does not exist, does not return a successful response, or times out, the deploy or restart can fail. The saved health check setting is not rolled back automatically.

`PUT /api/v1/projects/:id/health-check` saves the setting only. To apply saved runtime settings to the running app, call `POST /api/v1/projects/:id/restart`.


### POST /api/v1/projects/:id/restart

Description:
This endpoint keeps the `/restart` path for compatibility, but its actual behavior is to apply saved runtime settings to AppRun.

It uses the currently deployed image and does not rebuild source code. It applies the saved environment variables and health check setting to AppRun. If there are changes to apply, it creates a new AppRun version, verifies it, and then switches traffic. If there are no changes to apply, the operation is a no-op and no new deployment is created.

`PATCH /api/v1/projects/:id/env` and `PUT /api/v1/projects/:id/health-check` only save settings. To apply them to the running app, call this restart endpoint or redeploy the project.

Authentication:
Bearer token required.

Request:

```bash
curl -N -X POST "$BASE_URL/api/v1/projects/prj_123/restart" \
  -H "Authorization: Bearer $HANAMII_TOKEN"
```

Response `200`:

When a new version is created:

```json
{
  "project": {
    "id": "prj_123",
    "name": "my-api-test-app",
    "workspaceId": "ws_123",
    "status": "healthy",
    "createdAt": 1777622400000,
    "updatedAt": 1777622400000
  },
  "deployment": {
    "id": "dpl_123",
    "readyState": "READY",
    "errorCode": null
  }
}
```

When there are no changes to apply:

```json
{
  "project": {
    "id": "prj_123",
    "name": "my-api-test-app",
    "workspaceId": "ws_123",
    "status": "healthy",
    "createdAt": 1777622400000,
    "updatedAt": 1777622400000
  },
  "deployment": null,
  "noop": true,
  "message": "反映する変更はありません"
}
```

Error handling:
Restart can use a keepalive streaming response when processing takes time. Preflight errors such as undeployed projects, missing current version, missing deployed image, concurrent restart, permission failure, or rate limit are returned before streaming starts as error responses.

After streaming starts, runtime failures can still happen during app startup checks, health check access, timeout, or traffic switching. In that case, the HTTP status can remain `200` and the final JSON body can contain `error`. Clients must check the final JSON body `error`, not only the HTTP status.

If the app cannot respond to the configured health check, the response returns `health_check_failed`. In that case, the currently published version is maintained.

## Error Responses

All error responses use this shape:

```json
{
  "error": {
    "code": "validation_error",
    "message": "エラー内容"
  }
}
```

| Status | Code | Meaning |
|---|---|---|
| 400 | `validation_error` | Invalid input. |
| 401 | `unauthorized` | Authentication failed. |
| 403 | `forbidden` | Token scope or workspace role is insufficient, or a plan usage limit has been reached. |
| 404 | `not_found` | Resource does not exist or is not visible to the token. |
| 409 | `conflict` | Resource conflict such as duplicate project name. |
| 413 | `payload_too_large` | Request body is too large. |
| 415 | `unsupported_media_type` | JSON endpoint did not receive `Content-Type: application/json`. |
| 410 | `gone` | Resource expired, such as an export whose retention period has passed. |
| 429 | `rate_limited` | Rate limit exceeded. |
| 500 | `internal_error` | Internal server error. |
| 502 | `external_api_error` | The external service operation failed. Create/issue results may be unknown. |
| 503 | `service_unavailable` | The external service is unconfigured or temporarily unavailable. |

## Rate Limits

| Operation | Scope | Limit |
|---|---|---|
| Authentication attempts | IP | 60 / 60 seconds |
| Authentication failures | IP | 30 / 300 seconds |
| List/retrieve tokens | user | 120 / 60 seconds |
| Create token | user | 32 / 3600 seconds |
| Revoke token | user | 50 / 300 seconds |
| List workspaces | user | 120 / 60 seconds |
| List/retrieve projects | user | 500 / 60 seconds |
| Create project | workspace | 60 / 3600 seconds |
| Delete project | project | 30 / 300 seconds |
| Deploy/redeploy | project | 120 / 300 seconds |
| ZIP upload URL/check | token | 120 / 60 seconds |
| List project logs | project | 500 / 60 seconds |
| List environment variables | project | 500 / 60 seconds |
| Upsert environment variables | project | 120 / 60 seconds |
| Get health check setting | project | 500 / 60 seconds |
| Update health check setting | project | 120 / 60 seconds |
| Retrieve project database | project | 500 / 60 seconds |
| Create project database | project | 30 / 3600 seconds |
| Delete project database | project | 30 / 300 seconds |
| List database connection tokens | project | 120 / 60 seconds |
| Issue database connection token | project | 32 / 3600 seconds |
| Revoke database connection token | project | 50 / 300 seconds |
| Read database tables / rows | project | 500 / 60 seconds |
| Start database export | project | 10 / 3600 seconds |
| Retrieve export status / issue download URL | project | 120 / 60 seconds |
| Database import (upload session + start) | project | 20 / 3600 seconds |
| Storage bucket/file lists and usage (shared) | workspace | 500 / 60 seconds |
| Create Storage bucket | workspace | 30 / 3600 seconds |
| Delete Storage bucket | workspace | 30 / 300 seconds |
| List Storage keys | workspace | 120 / 60 seconds |
| Issue Storage key | workspace | 32 / 3600 seconds |
| Revoke Storage key | workspace | 50 / 300 seconds |
| Issue Storage viewing URL | workspace | 120 / 60 seconds |

Rate limit errors return `429 rate_limited`.

```json
{
  "error": {
    "code": "rate_limited",
    "message": "リクエスト数が上限を超えました"
  }
}
```

Rate limit responses include:

- `X-RateLimit-Limit`
- `X-RateLimit-Remaining`
- `X-RateLimit-Reset`

## Project Database

Each project can have one SQLite-compatible database (libSQL over HTTPS). The public API covers the same operations as the project's Database tab: create/delete, connection tokens, a read-only data viewer, export to a `.db` file, and import from a `.db` file.

Rules:
- `GET /api/v1/projects/:id/database` is available to every workspace role. All other database endpoints require the `owner` or `admin` role.
- Create, delete, and import are asynchronous. The response returns the database with a transitional `status` (`creating`, `activating`, `importing`, `deleting`). Poll `GET /api/v1/projects/:id/database` until `status` is `ready` (or the row disappears after delete).
- Connection tokens are shown in plaintext only in the issue response. hanamii does not store them.
- The data endpoints are read-only. There is no endpoint that accepts SQL text.
- When the database service cannot be reached, endpoints return `503 service_unavailable`. Retry after a short wait.

Database object:

| Field | Type | Description |
|---|---|---|
| `id` | string | Database ID. |
| `name` | string | Display name. May be empty. |
| `slug` | string | Name used in the connection URL. |
| `status` | string | `creating`, `activating`, `importing`, `ready`, `deleting`, or `failed`. |
| `hostname` | string \| null | Database host. `null` until the database is `ready`. |
| `failureReason` | string \| null | Reason when `status` is `failed`. |
| `createdAt` | number | Unix epoch milliseconds. |

### GET /api/v1/projects/:id/database

Description:
Retrieve the project database. Returns `database: null` when the project has no database.

Authentication:
Bearer token required.

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123/database"
```

Response `200`:

```json
{
  "database": {
    "id": "pdb_123",
    "name": "app db",
    "slug": "app-db-a1b2",
    "status": "ready",
    "hostname": "app-db-a1b2.db.hanamii.jp",
    "failureReason": null,
    "createdAt": 1777622400000
  }
}
```

### POST /api/v1/projects/:id/database

Description:
Create an empty database for the project. A project can have only one database. If a previous attempt ended in `failed`, the failed record is replaced.

Authentication:
Bearer token required. Role `owner` or `admin`.

Headers:

| Name | Required | Value |
|---|---|---|
| `Content-Type` | conditional | `application/json` when a body is sent. The body may be omitted. |

Request body:

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | string | no | Display name, up to 100 characters. When omitted or empty, `slug` is used for display. |

Request:

```bash
curl -X POST "$BASE_URL/api/v1/projects/prj_123/database" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{ "name": "app db" }'
```

Response `200`:

```json
{
  "database": {
    "id": "pdb_123",
    "name": "app db",
    "slug": "app-db-a1b2",
    "status": "creating",
    "hostname": null,
    "failureReason": null,
    "createdAt": 1777622400000
  }
}
```

Errors:
- `409 conflict`: the project already has a database, or a create/import is in progress.

### DELETE /api/v1/projects/:id/database

Description:
Delete the project database and all of its data. Deletion is asynchronous; the response returns `status: "deleting"`. A database in `creating`, `activating`, or `importing` cannot be deleted until it settles.

Authentication:
Bearer token required. Role `owner` or `admin`.

Request:

```bash
curl -X DELETE "$BASE_URL/api/v1/projects/prj_123/database" \
  -H "Authorization: Bearer $HANAMII_TOKEN"
```

Response `200`:

```json
{
  "database": {
    "id": "pdb_123",
    "name": "app db",
    "slug": "app-db-a1b2",
    "status": "deleting",
    "hostname": "app-db-a1b2.db.hanamii.jp",
    "failureReason": null,
    "createdAt": 1777622400000
  }
}
```

### GET /api/v1/projects/:id/database/auth-tokens

Description:
List connection tokens issued for the database. Plaintext tokens are never included.

Authentication:
Bearer token required. Role `owner` or `admin`.

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123/database/auth-tokens"
```

Response `200`:

```json
{
  "authTokens": [
    {
      "id": "dbtok_123",
      "name": "CI",
      "permission": "read_write",
      "status": "active",
      "createdAt": 1777622400000,
      "expiresAt": 1780214400000,
      "revokedAt": null
    }
  ]
}
```

### POST /api/v1/projects/:id/database/auth-tokens

Description:
Issue a connection token for the database. The plaintext `token` and the `databaseUrl` are returned only in this response. Use them with any libSQL client (`@libsql/client`, `libsql` CLI, Turso-compatible SDKs).

Authentication:
Bearer token required. Role `owner` or `admin`.

Headers:

| Name | Required | Value |
|---|---|---|
| `Content-Type` | conditional | `application/json` when a body is sent. The body may be omitted. |

Request body:

| Name | Type | Required | Description |
|---|---|---|---|
| `permission` | string | no | `read_write` (default) or `read_only`. |
| `ttlSeconds` | number | no | Lifetime in seconds. Default `2592000` (30 days). Values outside the range accepted by the database service return `400`. |
| `name` | string | no | Label shown in the token list, up to 100 characters. |

Request:

```bash
curl -X POST "$BASE_URL/api/v1/projects/prj_123/database/auth-tokens" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{ "permission": "read_write", "ttlSeconds": 2592000, "name": "CI" }'
```

Response `200`:

```json
{
  "authToken": {
    "id": "dbtok_123",
    "name": "CI",
    "permission": "read_write",
    "status": "active",
    "createdAt": 1777622400000,
    "expiresAt": 1780214400000,
    "revokedAt": null
  },
  "token": "eyJhbGciOi...",
  "databaseUrl": "libsql://app-db-a1b2.db.hanamii.jp"
}
```

Rules:
- The database must be `ready`; otherwise `400 validation_error` is returned.
- Store `token` as a secret. It cannot be retrieved again.

### DELETE /api/v1/projects/:id/database/auth-tokens/:tokenId

Description:
Revoke a connection token. Revocation takes effect immediately.

Authentication:
Bearer token required. Role `owner` or `admin`.

Request:

```bash
curl -X DELETE "$BASE_URL/api/v1/projects/prj_123/database/auth-tokens/dbtok_123" \
  -H "Authorization: Bearer $HANAMII_TOKEN"
```

Response `200`:

```json
{
  "authToken": {
    "id": "dbtok_123",
    "status": "revoked"
  }
}
```

### GET /api/v1/projects/:id/database/tables

Description:
List user tables with their column definitions. System tables (`sqlite_*`) are excluded. Read-only.

Authentication:
Bearer token required. Role `owner` or `admin`.

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123/database/tables"
```

Response `200`:

```json
{
  "tables": [
    {
      "name": "users",
      "columns": [
        { "name": "id", "type": "INTEGER", "isPrimaryKey": true, "isNotNull": true },
        { "name": "email", "type": "TEXT", "isPrimaryKey": false, "isNotNull": true }
      ]
    }
  ]
}
```

### GET /api/v1/projects/:id/database/tables/:table/rows

Description:
Read rows of one table with offset pagination. Read-only. The table name must match a table returned by the tables endpoint; otherwise `404` is returned.

Authentication:
Bearer token required. Role `owner` or `admin`.

Query parameters:

| Name | Type | Required | Description |
|---|---|---|---|
| `limit` | number | no | Rows per page. Default `50`, clamped to 1–100. |
| `offset` | number | no | Rows to skip. Default `0`, clamped to 0–1,000,000. |

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123/database/tables/users/rows?limit=50&offset=0"
```

Response `200`:

```json
{
  "table": "users",
  "rows": [
    { "id": 1, "email": "alice@example.com", "avatar": { "kind": "blob", "bytes": 5120 } }
  ],
  "pagination": {
    "limit": 50,
    "offset": 0,
    "totalCount": 1,
    "totalCountTruncated": false
  }
}
```

Rules:
- `totalCount` stops counting at 100,000. When more rows exist, `totalCount` is `100000` and `totalCountTruncated` is `true`.
- Cell values: `NULL` is `null`. BLOBs are returned as `{ "kind": "blob", "bytes": <length> }` without contents. Text longer than 1,000 characters is returned as `{ "kind": "text", "value": "<first 1000 chars>", "truncated": true }`. Integers beyond the safe JavaScript range are returned as strings.
- Reads time out after 10 seconds and return `503`.

### POST /api/v1/projects/:id/database/exports

Description:
Start an export. The export produces a standard single-file SQLite `.db` that reflects the database at the moment the export starts. Poll the job status, then issue a download URL when `status` is `ready`.

Authentication:
Bearer token required. Role `owner` or `admin`.

Headers:

| Name | Required | Value |
|---|---|---|
| `Idempotency-Key` | no | Any string up to 255 characters. Re-sending the same key returns the same job instead of starting another export. When omitted (and `idempotencyKey` is not in the body), each call starts a new export. |
| `Content-Type` | conditional | `application/json` when a body is sent. The body may be omitted. |

Request body:

| Name | Type | Required | Description |
|---|---|---|---|
| `idempotencyKey` | string | no | Same meaning as the `Idempotency-Key` header. The header takes priority. |

Request:

```bash
curl -X POST "$BASE_URL/api/v1/projects/prj_123/database/exports" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Idempotency-Key: nightly-2026-09-04"
```

Response `200`:

```json
{
  "exportJob": {
    "id": "exp_123",
    "status": "queued",
    "failureCode": null,
    "artifactSizeBytes": null,
    "artifactSha256": null,
    "artifactAvailableUntil": null,
    "createdAt": 1777622400000
  }
}
```

Rules:
- `status` is one of `queued`, `running`, `validating`, `uploading`, `ready`, `cancelled`, `failed`, `expired`. `ready`, `cancelled`, `failed`, and `expired` are terminal.
- The database service limits exports to 20 per hour per organization and 10 per hour per user. Exceeding this returns `429 rate_limited`.
- Finished files are retained for 24 hours (`artifactAvailableUntil`).

### GET /api/v1/projects/:id/database/exports/:exportJobId

Description:
Retrieve the export job status.

Authentication:
Bearer token required. Role `owner` or `admin`.

Request:

```bash
curl -H "Authorization: Bearer $HANAMII_TOKEN" \
  "$BASE_URL/api/v1/projects/prj_123/database/exports/exp_123"
```

Response `200`:

```json
{
  "exportJob": {
    "id": "exp_123",
    "status": "ready",
    "failureCode": null,
    "artifactSizeBytes": 1048576,
    "artifactSha256": "3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "artifactAvailableUntil": 1777708800000,
    "createdAt": 1777622400000
  }
}
```

### POST /api/v1/projects/:id/database/exports/:exportJobId/download

Description:
Issue a signed download URL for a finished export. The URL expires after at most 10 minutes. While the file is retained (`availableUntil`), this endpoint can be called again to get a fresh URL.

Authentication:
Bearer token required. Role `owner` or `admin`.

Request:

```bash
curl -X POST "$BASE_URL/api/v1/projects/prj_123/database/exports/exp_123/download" \
  -H "Authorization: Bearer $HANAMII_TOKEN"

# Then download the file (no Authorization header; the URL is signed):
curl -L -o app.db "<download.url>"
```

Response `200`:

```json
{
  "download": {
    "url": "https://object-storage.example.com/exports/app-db-a1b2.db?X-Amz-Signature=...",
    "urlExpiresAt": 1777623000000,
    "availableUntil": 1777708800000,
    "sizeBytes": 1048576,
    "sha256": "3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "fileName": "app-db-a1b2.db"
  }
}
```

Errors:
- `410 gone`: the retention period has passed. Start a new export.
- `400 validation_error`: the job is not `ready` yet.

### POST /api/v1/projects/:id/database/import-session

Description:
Create the database from an existing SQLite file (import), step 1 of 2. Declare the file size and receive signed upload URLs. The upload is always split into parts; each part must be uploaded with a `PUT` whose body length is exactly `contentLength`. Collect the `ETag` response header of every part for step 2.

Authentication:
Bearer token required. Role `owner` or `admin`.

Headers:

| Name | Required | Value |
|---|---|---|
| `Content-Type` | yes | `application/json` |

Request body:

| Name | Type | Required | Description |
|---|---|---|---|
| `fileSizeBytes` | number | yes | Exact size of the `.db` file in bytes. Maximum 104,857,600 (100 MiB). |

Request:

```bash
FILE=./app.db
SIZE=$(stat -f%z "$FILE" 2>/dev/null || stat -c%s "$FILE")

curl -X POST "$BASE_URL/api/v1/projects/prj_123/database/import-session" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data "{ \"fileSizeBytes\": $SIZE }"
```

Response `200`:

```json
{
  "session": {
    "sessionId": "imp_123",
    "partSizeBytes": 8388608,
    "parts": [
      { "partNumber": 1, "url": "https://object-storage.example.com/...part1?X-Amz-Signature=...", "contentLength": 8388608 },
      { "partNumber": 2, "url": "https://object-storage.example.com/...part2?X-Amz-Signature=...", "contentLength": 1048576 }
    ],
    "expiresAt": 1777626000000
  }
}
```

Upload each part (example with `split` and `curl`):

```bash
# Split the file into partSizeBytes chunks: app.db.part.aa, app.db.part.ab, ...
split -b 8388608 "$FILE" app.db.part.

# Upload part 1 and capture its ETag. Repeat for every part in order.
curl -s -D - -o /dev/null -X PUT "<parts[0].url>" \
  -H "Content-Type: application/octet-stream" \
  --data-binary "@app.db.part.aa" | grep -i '^etag:'
```

Rules:
- Upload URLs expire at `expiresAt`. Create a new session if they expire.
- The project must not already have a database (except a `failed` one), otherwise `409 conflict` is returned.

### POST /api/v1/projects/:id/database/import-start

Description:
Import step 2 of 2. Send the `ETag` of every uploaded part to start the import. The response returns the database with `status: "importing"`. Poll `GET /api/v1/projects/:id/database` until it becomes `ready` or `failed`.

Authentication:
Bearer token required. Role `owner` or `admin`.

Headers:

| Name | Required | Value |
|---|---|---|
| `Content-Type` | yes | `application/json` |

Request body:

| Name | Type | Required | Description |
|---|---|---|---|
| `sessionId` | string | yes | `session.sessionId` from the import-session response. |
| `parts` | array | yes | At least one item; include one item per uploaded part. |
| `parts[].partNumber` | number | yes | Part number from the session. Must be an integer greater than or equal to 1. |
| `parts[].etag` | string | yes | Non-empty `ETag` response header value of that part's PUT, including quotes if present. |
| `name` | string | no | Display name, up to 100 characters. |

Request:

```bash
curl -X POST "$BASE_URL/api/v1/projects/prj_123/database/import-start" \
  -H "Authorization: Bearer $HANAMII_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{
    "name": "app db",
    "sessionId": "imp_123",
    "parts": [
      { "partNumber": 1, "etag": "\"9b2cf535f27731c974343645a3985328\"" },
      { "partNumber": 2, "etag": "\"e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6\"" }
    ]
  }'
```

Response `200`:

```json
{
  "database": {
    "id": "pdb_123",
    "name": "app db",
    "slug": "app-db-a1b2",
    "status": "importing",
    "hostname": null,
    "failureReason": null,
    "createdAt": 1777622400000
  }
}
```

Rules:
- The uploaded file must be a valid SQLite database. Validation failures end with `status: "failed"` and a `failureReason`; delete the failed record with `DELETE /api/v1/projects/:id/database` or simply create/import again.

## Object Storage (beta)

Storage management uses the same Hanamii API token and base URL as other `/api/v1` operations. A workspace-scoped token cannot access a different workspace, even if its owner belongs to both. Membership and role are checked on every request. Bucket/file listing, viewing URLs and usage allow all members; bucket creation/deletion and every access-key management operation require owner/admin.

File uploads, file deletion and share URLs use the **separate file API**, at `apiOrigin` returned by the bucket list, with a **bucket-specific Storage key**. A Hanamii API token is not a Storage key. Do not send the internal service key or a Hanamii API token to the file API. See the [file API guide](/docs/guides/object-storage) for all file endpoints.

The file API's `POST /v1/files/uploads` requires all four JSON fields:

| Field | Type | Required value |
|---|---|---|
| `name` | string | File name, 1–255 characters, without line breaks |
| `sizeBytes` | string | Positive file size in bytes, expressed as a decimal string |
| `contentType` | string | MIME type, 1–255 characters, without line breaks |
| `contentMd5` | string | Standard Base64 encoding of the entire file's 16-byte MD5 digest: 24 characters ending in `==` |

Missing or malformed `contentMd5` returns `400 VALIDATION_ERROR`. Compute it from the file contents, for example with `openssl dgst -md5 -binary "$FILE" | openssl base64 -A`; a hexadecimal digest is not accepted. Send the returned `headers`, including `Content-MD5`, unchanged with the signed PUT request.

For bodyless POST requests such as file completion and viewing-URL issuance, curl examples must include `-H 'Content-Length: 0'`. Some hosting environments reject an unspecified length with HTTP 411 (`No Content Length`). Requests using `--data` already have their body length set by curl.

### Management contracts

- All responses, including errors and plaintext key issuance, use `Cache-Control: no-store`.
- Storage timestamps (`createdAt`, `updatedAt`, `lastUsedAt`, `expiresAt`) are ISO 8601 strings, unlike the general epoch-millisecond convention above. Nullable timestamps remain `null`.
- Bucket, file and key lists return `{ "items": [...], "nextCursor": "..." }`. Pass `nextCursor` as `?cursor=...`; `null` ends pagination. Bucket pages contain up to 100 items; key and file pages up to 50. These sizes are fixed: limit/until/since are ignored for Storage. Omit cursor for the first page; an empty value also starts at the first page. When nextCursor is null, stop rather than sending ?cursor=null. URL-encode the opaque cursor (1–1024 printable ASCII characters). The cursor is opaque; do not decode or invent it. The bucket list also returns `apiOrigin`.
- Create-bucket JSON: `{ "name": "assets", "visibility": "private" }`. Both fields are required. Names have 3–63 lowercase letters/digits/hyphens, starting and ending with a letter or digit. `visibility` is `public` or `private` and cannot be changed later. Free workspaces can create only private buckets. An unresolved plan stops creation with `503 service_unavailable`, even when usage can still return `limits: null`; this does not necessarily mean a network outage. Success is `201` with `{ id, name, visibility, createdAt }`.
- Issue-key JSON: `{ "permission": "read_write" }` or `{ "permission": "read_only" }`. Success is `201` with `{ keyId, permission, createdAt, key }`; plaintext `key` appears only in this response. Listing keys returns metadata, never plaintext: createdBy is the issuer user ID; creatorEmail is present only while that user remains a member, otherwise null.
- File lists return `{ id, name, sizeBytes, contentType, createdAt, updatedAt }`; they contain no delivery URL. Issue a viewing URL when needed: `POST .../files/:fileId/view-url`, with no body. The result is `{ url, expiresAt }`: public files have a fixed URL and `expiresAt: null`, private files have a one-hour signed URL.
- Usage returns `{ usedBytes, fileCount, deliveredBytes, limits }`. Values and limit values are decimal strings. `limits` is `{ maxBuckets, maxTotalBytes, maxFiles, maxFileBytes }` or `null` when the plan cannot be resolved. Delivery usage is a monthly Tokyo-time estimate, not an upload limit. While payment is restricted/suspended, all four limit values are "0": new buckets/uploads stop, while existing reads/delivery continue. Treat that state separately and never divide usage by zero. usedBytes excludes upload reservations, so the file API may reject an upload with 422 even when usedBytes is below the limit. Unknown plans return limits:null. Internal infrastructure details are omitted.
- Revoke-key returns `204` with no body, including repeated revocation. Bucket deletion returns `202 { "status": "processing" }` while file cleanup continues or `204` when complete. Existing delivery URLs may remain reachable during cleanup and cache expiry. Revoking a key does not invalidate already-issued signed PUT or private delivery URLs; they remain valid until expiry. Repeating deletion of an already-deleted bucket returns 202 or 204; that is different from a nonexistent ID returning 404.
- Errors use the standard `{ "error": { "code": "...", "message": "..." } }` shape. Missing/expired/revoked API tokens return `401`; scope/role/plan restrictions return `403`; missing bucket/key/file targets return `404` for target operations; upstream 404 for bucket listing, usage or bucket creation becomes `502`; duplicate names return `409`; invalid JSON/fields return `400`; non-JSON bodies return `415`; bodies larger than 16 KiB return `413`; action limits return `429` with the usual rate-limit headers; Storage connection failures return `502`/`503`.
- If a create/issue response is lost or fails, do not blindly repeat it: list the buckets/keys first and revoke any unwanted key. Plaintext from a lost issuance response cannot be recovered.

Rate limits apply per workspace: bucket/file/usage reads share 500/minute; bucket creation 30/hour; bucket deletion 30/5 minutes; key listing 120/minute; key issuance 32/hour; key revocation 50/5 minutes; viewing URL issuance 120/minute. Authentication limits also apply.

### Safe server-side examples and operation-specific errors

TypeScript examples run on the server and use the server environment variable `HANAMII_TOKEN`. Next.js examples import `server-only`; they are internal helpers, not Server Actions. Authenticate the application user and authorize the target workspace before exposing a route that calls these helpers. Never serialize plaintext keys into browser responses or Server Component props. Key issuance requires a server-side `storeKey` callback, receives the secret once, and returns only key metadata. Do not use console output as the callback. Viewing URLs may be sent to an authorized viewer but must not be logged.

Use IDs returned by the API. Bucket/file IDs have 1–128 ASCII letters, digits, underscores or hyphens. A key ID is `key_` followed by 24 letters, digits, underscores or hyphens; it is not the plaintext key. JSON bodies must be objects, no larger than 16 KiB. `name`, `visibility`, and `permission` are required where documented. The general limit/until/since pagination convention above does not apply to Storage.

Common authentication, role/scope, action-limit and infrastructure failures are 401, 403, 429, 500 and 502/503. The following lists the main operation-specific responses; it is not an exhaustive list of every infrastructure failure.

| Operation | Additional responses and meaning |
|---|---|
| List buckets | 400 invalid cursor; upstream 404 is 502, not a missing-bucket response |
| Create bucket | 400 invalid input; 403 free public bucket, quota or payment restriction; 409 duplicate name; 413 body too large; 415 non-JSON; 503 unresolved plan. Upstream 404 becomes 502 |
| Delete bucket | 400 invalid ID; 404 nonexistent ID; 409 conflict; 202 processing or 204 complete on repeat deletion |
| List keys/files | 400 invalid ID/cursor; 404 missing bucket; 409 conflict |
| Issue key | 400 invalid ID/permission; 404 missing bucket; 409 conflict; 413 body too large; 415 non-JSON |
| Revoke key | 400 invalid ID; 404 missing target; 409 conflict; 204 also for an already-revoked key |
| View URL | 400 invalid ID; 404 missing bucket/file; 409 conflict |
| Usage | Upstream 404 becomes 502; limits may be null or zero as explained above |

Example error bodies (the Storage file API uses a different contract with uppercase codes and requestId):

```json
{"error":{"code":"external_api_error","message":"オブジェクトストレージの操作に失敗しました"}}
```

The exact validation message depends on the field. For 5xx, the message is the fixed `オブジェクトストレージの操作に失敗しました`; internal errors and upstream response bodies are not returned. A failed create/issue may have succeeded upstream: stop, list the resources and inspect them instead of blindly repeating the mutation.

### cURL walkthrough for development

Requirements: `curl`, `jq`, `openssl`. Use a workspace and test files you control. Set `BASE_URL` to the frontend development origin and `HANAMII_TOKEN` to a Hanamii API token belonging to its owner/admin. This walkthrough creates a dedicated test bucket. Set `BASE_URL`, `WORKSPACE_ID`, and `HANAMII_TOKEN` in your shell first; do not enable shell tracing or paste credentials into logs. Keep room for a new bucket (a free workspace has only one private bucket). Repeat with `VISIBILITY=public` in a paid workspace to check public delivery. The script stops on unexpected responses, retries completion HTTP 409 for the same file at most 20 times, and cleans up API resources only after every assertion succeeds. On failure, inspect and remove the dedicated test resources manually; do not blindly rerun bucket/key creation.

```sh
(
set +x
set -eu
: "${BASE_URL:?Set the frontend development origin}"
: "${WORKSPACE_ID:?Set the test workspace UUID}"
: "${HANAMII_TOKEN:?Set its owner/admin Hanamii token}"
VISIBILITY=${VISIBILITY:-private}
case "$VISIBILITY" in private|public) ;; *) exit 1 ;; esac
BUCKET_NAME="storage-api-$(openssl rand -hex 8)"

# Capture without printing bodies, keys, signed URLs, or curl diagnostics.
capture() {
  RAW=$(curl --silent --connect-timeout 10 --max-time 60 \
    --write-out '\n%{http_code}' "$@" 2>/dev/null) || {
    printf '%s\n' 'Network request failed; stop and inspect the test resources.' >&2
    return 1
  }
  HTTP_STATUS=$(printf '%s\n' "$RAW" | tail -n 1)
  HTTP_BODY=$(printf '%s\n' "$RAW" | sed '$d')
}
request() {
  EXPECTED=$1
  shift
  capture "$@" || return 1
  case " $EXPECTED " in
    *" $HTTP_STATUS "*) printf '%s' "$HTTP_BODY" ;;
    *) printf 'Unexpected HTTP %s; stop and inspect the test resources.\n' "$HTTP_STATUS" >&2
       return 1 ;;
  esac
}

# 1. Do not retry create/key issuance when the result is unknown.
MANAGEMENT="$BASE_URL/api/v1/workspaces/$WORKSPACE_ID/storage"
BUCKET_JSON=$(request 201 -X POST "$MANAGEMENT/buckets" \
  -H "Authorization: Bearer $HANAMII_TOKEN" -H 'Content-Type: application/json' \
  --data "$(jq -n --arg name "$BUCKET_NAME" --arg visibility "$VISIBILITY" \
    '{name:$name,visibility:$visibility}')")
BUCKET_ID=$(printf '%s' "$BUCKET_JSON" | jq -er '.id | strings | select(test("^[A-Za-z0-9_-]{1,128}$"))')
LIST_JSON=$(request 200 "$MANAGEMENT/buckets" -H "Authorization: Bearer $HANAMII_TOKEN")
HANAMII_STORAGE_URL=$(printf '%s' "$LIST_JSON" | jq -er '.apiOrigin | strings | select(startswith("https://"))')
KEY_JSON=$(request 201 -X POST "$MANAGEMENT/buckets/$BUCKET_ID/access-keys" \
  -H "Authorization: Bearer $HANAMII_TOKEN" -H 'Content-Type: application/json' \
  --data '{"permission":"read_write"}')
WRITE_KEY_ID=$(printf '%s' "$KEY_JSON" | jq -er '.keyId | strings | select(length > 0)')
WRITE_KEY=$(printf '%s' "$KEY_JSON" | jq -er '.key | strings | select(length > 0)')

# 2. Create only a local temporary payload; the trap never deletes API resources.
FILE=$(mktemp "${TMPDIR:-/tmp}/hanamii-storage-test.XXXXXX")
trap 'rm -f "$FILE"' 0
printf 'Storage API test\n' > "$FILE"
SIZE=$(wc -c < "$FILE" | tr -d ' ')
MD5=$(openssl dgst -md5 -binary "$FILE" | openssl base64 -A)
UPLOAD_BODY=$(jq -n --arg size "$SIZE" --arg md5 "$MD5" \
  '{name:"storage-api-test.txt",sizeBytes:$size,contentType:"text/plain",contentMd5:$md5}')
UPLOAD_JSON=$(request 201 -X POST "$HANAMII_STORAGE_URL/v1/files/uploads" \
  -H "Authorization: Bearer $WRITE_KEY" -H 'Content-Type: application/json' --data "$UPLOAD_BODY")
FILE_ID=$(printf '%s' "$UPLOAD_JSON" | jq -er '.fileId | strings | select(length > 0)')
UPLOAD_URL=$(printf '%s' "$UPLOAD_JSON" | jq -er '.uploadUrl | strings | select(startswith("https://"))')

# 3. Use exactly the returned headers and send no API token to the signed PUT URL.
request 200 -X PUT "$UPLOAD_URL" \
  -H "Content-Type: $(printf '%s' "$UPLOAD_JSON" | jq -er '.headers["Content-Type"]')" \
  -H "Content-Length: $(printf '%s' "$UPLOAD_JSON" | jq -er '.headers["Content-Length"]')" \
  -H "Content-Disposition: $(printf '%s' "$UPLOAD_JSON" | jq -er '.headers["Content-Disposition"]')" \
  -H "Content-MD5: $(printf '%s' "$UPLOAD_JSON" | jq -er '.headers["Content-MD5"]')" \
  --data-binary @"$FILE" > /dev/null

# Retry only completion HTTP 409, for the same fileId, at most 20 attempts.
ATTEMPT=1
while :; do
  capture -X POST "$HANAMII_STORAGE_URL/v1/files/$FILE_ID/complete" \
    -H "Authorization: Bearer $WRITE_KEY" -H 'Content-Length: 0'
  case "$HTTP_STATUS" in
    200) break ;;
    409) if [ "$ATTEMPT" -ge 20 ]; then
           printf '%s\n' 'Completion still pending; stop without automatic cleanup.' >&2
           exit 1
         fi
         ATTEMPT=$((ATTEMPT + 1))
         sleep 3 ;;
    *) printf 'Completion failed: HTTP %s; stop without automatic cleanup.\n' "$HTTP_STATUS" >&2
       exit 1 ;;
  esac
done

# 4. Hanamii management reads and viewing URL; never print the URL.
request 200 "$MANAGEMENT/buckets/$BUCKET_ID/files" \
  -H "Authorization: Bearer $HANAMII_TOKEN" > /dev/null
VIEW_JSON=$(request 200 -X POST "$MANAGEMENT/buckets/$BUCKET_ID/files/$FILE_ID/view-url" \
  -H "Authorization: Bearer $HANAMII_TOKEN" -H 'Content-Length: 0')
VIEW_URL=$(printf '%s' "$VIEW_JSON" | jq -er '.url | strings | select(startswith("https://"))')
request 200 "$VIEW_URL" > /dev/null
case "$VISIBILITY" in private) UNSIGNED_STATUS=403 ;; public) UNSIGNED_STATUS=200 ;; esac
request "$UNSIGNED_STATUS" "${VIEW_URL%%\?*}" > /dev/null

# 5. Expected, in order: 200, 403, 403. Any mismatch stops before cleanup.
READER_JSON=$(request 201 -X POST "$MANAGEMENT/buckets/$BUCKET_ID/access-keys" \
  -H "Authorization: Bearer $HANAMII_TOKEN" -H 'Content-Type: application/json' \
  --data '{"permission":"read_only"}')
READ_KEY_ID=$(printf '%s' "$READER_JSON" | jq -er '.keyId | strings | select(length > 0)')
READ_KEY=$(printf '%s' "$READER_JSON" | jq -er '.key | strings | select(length > 0)')
request 200 "$HANAMII_STORAGE_URL/v1/files" -H "Authorization: Bearer $READ_KEY" > /dev/null
request 403 -X POST "$HANAMII_STORAGE_URL/v1/files/uploads" \
  -H "Authorization: Bearer $READ_KEY" -H 'Content-Type: application/json' --data "$UPLOAD_BODY" > /dev/null
request 403 -X DELETE "$HANAMII_STORAGE_URL/v1/files/$FILE_ID" \
  -H "Authorization: Bearer $READ_KEY" > /dev/null
# read_only may share a private file for 60 seconds; public files use their fixed URL.
if [ "$VISIBILITY" = private ]; then
  READER_VIEW=$(request 200 -X POST "$HANAMII_STORAGE_URL/v1/files/$FILE_ID/share-url" \
    -H "Authorization: Bearer $READ_KEY" -H 'Content-Type: application/json' \
    --data '{"expiresInSeconds":60}')
  READER_URL=$(printf '%s' "$READER_VIEW" | jq -er '.url | strings | select(startswith("https://"))')
  request 200 "$READER_URL" > /dev/null
else
  request 409 -X POST "$HANAMII_STORAGE_URL/v1/files/$FILE_ID/share-url" \
    -H "Authorization: Bearer $READ_KEY" -H 'Content-Type: application/json' \
    --data '{"expiresInSeconds":60}' > /dev/null
fi
request 200 "$MANAGEMENT/usage" -H "Authorization: Bearer $HANAMII_TOKEN" > /dev/null

# 6. Only after every check succeeds, remove this run's file, keys, and bucket.
request 204 -X DELETE "$HANAMII_STORAGE_URL/v1/files/$FILE_ID" \
  -H "Authorization: Bearer $WRITE_KEY" > /dev/null
for KEY_ID in "$READ_KEY_ID" "$WRITE_KEY_ID"; do
  request 204 -X DELETE "$MANAGEMENT/buckets/$BUCKET_ID/access-keys/$KEY_ID" \
    -H "Authorization: Bearer $HANAMII_TOKEN" > /dev/null
done
request '202 204' -X DELETE "$MANAGEMENT/buckets/$BUCKET_ID" \
  -H "Authorization: Bearer $HANAMII_TOKEN" > /dev/null
printf '%s\n' 'Storage API checks passed; test resource cleanup accepted.'
)
```

Delivery checks must be performed against the deployed CDN configuration. Local mock tests do not verify domain, TLS, or private-site signature enforcement. File deletion releases workspace capacity; delivery accounting updates after access logs are collected, not immediately after a request.
