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

# Create a Template and start its initial Build

> Creates a logical Template together with its initial Build. The initial
Build is created and started from the required `build` definition in the
same request. A dockerfile that references an uploaded file
(`{{file:...}}`) cannot be used here (400): create the Template without
`build`, upload the file, then start the waiting Build.

`Idempotency-Key` is required and acts as the idempotency key because Template
creation can complete after an upstream timeout; a keyless retry would build a
second Template. Repeating the request with identical parameters replays the
same Template/Build (with `Idempotency-Replayed: true`); a different body under
the same key returns 400 `Sandbox.IdempotentParameterMismatch`; after the
Template is deleted the key answers 409 `Sandbox.IdempotentKeyConsumed`. Keys
are remembered for 24 hours. (`X-Request-ID` is trace-only and server-generated.)

`resources` selects a catalog preset, e.g.
`{"type":"preset","product":"gmi.sandbox.x-large"}`. The `product`
value is the catalog SKU (see `GET /api/v2/products`); the service
resolves the active entry from the product catalog.




## OpenAPI

````yaml /api-spec/sandbox_api.yaml post /templates
openapi: 3.0.3
info:
  title: GMI Sandbox API
  description: >-
    REST API for GMI Sandbox: create isolated execution environments from
    templates or durable snapshots, manage their lifecycle on the control plane,
    and run commands or transfer files through each sandbox's own data plane.
  contact:
    name: GMI Cloud Support
    email: support@gmicloud.ai
  version: '2.0'
servers:
  - url: https://console.gmicloud.ai/api/v2
    description: Control plane
security:
  - bearerAuth: []
tags:
  - name: Sandbox
    description: |
      Sandbox instance lifecycle management (Sandbox v2, /api/v2/sandboxes)
  - name: SandboxSnapshot
    description: Durable sandbox snapshot management (Sandbox v2, `/api/v2/snapshots`)
  - name: SandboxTemplate
    description: Sandbox template management (Sandbox v2, `/api/v2/templates`)
  - name: Sandbox-Exec
    description: >
      Sandbox execution data plane (accessed via the sandbox host and sandbox
      access token). These endpoints are not under the control plane's `/api/v2`
      path; clients connect directly to `https://{sandbox_key}.{domain}` and
      authenticate with `X-Access-Token`.
  - name: Sandbox-Shell
    description: >
      Sandbox interactive terminal (PTY) data plane. **These endpoints are not
      under `/api/v2`**: clients connect directly to
      `https://{sandbox_key}.{domain}` and authenticate with `X-Access-Token`.
      `{sandbox_key}`, `{domain}` and the `X-Access-Token` value are the
      `sandbox_key`, `domain` and `sandbox_access_token` returned by the
      control-plane create/connect endpoints; no extra endpoint is needed.


      Each sandbox has exactly **one logical shell session** and at most **one
      active WebSocket connection** at a time (a second concurrent attach is
      refused at handshake with `409`). Disconnecting does not destroy the shell
      — re-attaching resumes the same session; only `POST /shell/control` with
      `action=close` destroys it.
  - name: Sandbox-Files
    description: >
      Sandbox file data plane (`/files`). **These endpoints are not under
      `/api/v2`** and do not use `Authorization: Bearer`: they are served by the
      sandbox's own data-plane entry point — clients connect directly to
      `https://{sandbox_key}.{domain}` and authenticate with `X-Access-Token`.
      `{sandbox_key}` is the `sandbox_key` returned by the create/connect
      endpoints, used for data-plane host addressing. `{domain}` and
      `X-Access-Token` are the `domain` and `sandbox_access_token` from the same
      responses — no extra endpoint is needed to obtain them.


      This split is not historical baggage but the nature of a data plane: file
      transfer is long-lived, high-volume, and addressed per sandbox, differing
      from the control plane's short requests in both capacity model and failure
      domain, so they do not share an entry point.


      **One unified abstraction.** The same contract is served by two backend
      kinds (an in-sandbox file service / a data-center data-plane proxy);
      clients need not — and cannot — tell them apart. The cost is that the
      contract is their intersection: `Content-Length` on download and resumable
      download (`Range`/`206`) are **optional capabilities** that vary by data
      center, and clients must work correctly when they are absent. See the
      per-operation notes below.
paths:
  /templates:
    post:
      tags:
        - SandboxTemplate
      summary: Create a Template and start its initial Build
      description: >
        Creates a logical Template together with its initial Build. The initial

        Build is created and started from the required `build` definition in the

        same request. A dockerfile that references an uploaded file

        (`{{file:...}}`) cannot be used here (400): create the Template without

        `build`, upload the file, then start the waiting Build.


        `Idempotency-Key` is required and acts as the idempotency key because
        Template

        creation can complete after an upstream timeout; a keyless retry would
        build a

        second Template. Repeating the request with identical parameters replays
        the

        same Template/Build (with `Idempotency-Replayed: true`); a different
        body under

        the same key returns 400 `Sandbox.IdempotentParameterMismatch`; after
        the

        Template is deleted the key answers 409 `Sandbox.IdempotentKeyConsumed`.
        Keys

        are remembered for 24 hours. (`X-Request-ID` is trace-only and
        server-generated.)


        `resources` selects a catalog preset, e.g.

        `{"type":"preset","product":"gmi.sandbox.x-large"}`. The `product`

        value is the catalog SKU (see `GET /api/v2/products`); the service

        resolves the active entry from the product catalog.
      operationId: createTemplate
      parameters:
        - $ref: '#/components/parameters/IdempotencyKeyRequiredParam'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateTemplateRequest'
      responses:
        '201':
          description: |
            The Template record is created and immediately addressable: `GET
            /templates/{id}` works right away, and a failed initial Build
            leaves a rebuildable Template rather than erasing it. Build
            readiness is reported by `status`, not by the status code.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TemplateMutationAccepted'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          description: >
            State conflict (`Resource.StateConflict` or an operation-specific
            code), or the selected IDC is under maintenance
            (`IDC.UnderMaintenance`): write operations are rejected until the
            IDC is usable again. Read operations are unaffected. A Template with
            the same name already exists: `Resource.AlreadyExists`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '422':
          $ref: '#/components/responses/Unsupported'
        '429':
          $ref: '#/components/responses/QuotaExceeded'
        '499':
          $ref: '#/components/responses/RequestCanceled'
        '500':
          $ref: '#/components/responses/InternalError'
        '502':
          $ref: '#/components/responses/UpstreamError'
        '504':
          $ref: '#/components/responses/RequestTimeout'
components:
  parameters:
    IdempotencyKeyRequiredParam:
      name: Idempotency-Key
      in: header
      required: true
      description: |
        Caller-generated key that makes the mutation safe to retry (a UUID is
        recommended). Matched byte-for-byte: 1-64 printable ASCII characters,
        no whitespace. The same key with a different request body returns 400
        Sandbox.IdempotentParameterMismatch. Echoed on responses; replays add
        Idempotency-Replayed: true. Keys are remembered for 24 hours.
      schema:
        type: string
        minLength: 1
        maxLength: 64
  schemas:
    CreateTemplateRequest:
      type: object
      additionalProperties: false
      required:
        - name
        - resources
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 64
          pattern: ^[A-Za-z0-9_-]+$
          description: Organization-scoped Template display name.
        description:
          type: string
          maxLength: 256
          description: Human-readable Template description.
        idc_name:
          type: string
          description: >
            IDC that permanently owns the Template. Optional: omitted, empty,
            and whitespace-only values are equivalent — the organization's
            configured default data center is used (maintained by the platform
            administrator; the same setting used by sandbox creation). If the
            organization has no default configured, the request returns 400. If
            the effective data center is under maintenance, the request returns
            409 `IDC.UnderMaintenance`.
        resources:
          $ref: '#/components/schemas/ResourceSelection'
        labels:
          type: object
          maxProperties: 64
          description: User-defined labels used for filtering.
          additionalProperties:
            type: string
            maxLength: 256
        build:
          allOf:
            - $ref: '#/components/schemas/InitialBuildDefinition'
          description: |
            Initial Build definition created and started with the Template
            (combined flow, every IDC supports it). A `file_context` cannot be
            attached here; use the split flow when files are required. Omitting
            `build` selects the split flow: the Template and a `waiting`
            initial Build are created without starting anything, and the Build
            is started later via `POST /templates/{template_id}/builds/{id}`.
            The split flow is not supported in every IDC; unsupported IDCs
            reject it with 422.
    TemplateMutationAccepted:
      type: object
      additionalProperties: false
      required:
        - request_id
        - data
      properties:
        request_id:
          type: string
          description: HTTP request correlation identifier.
        data:
          type: object
          additionalProperties: false
          required:
            - id
            - build_id
            - status
          properties:
            id:
              type: string
              description: Created GMI Template identifier.
            build_id:
              type: string
              description: Created initial or snapshot Build identifier.
            status:
              $ref: '#/components/schemas/BuildStatus'
    ErrorResponse:
      type: object
      required:
        - code
        - message
        - request_id
      properties:
        code:
          type: string
          description: Machine-readable business error code
          example: Resource.QuotaExceeded
        message:
          type: string
          description: Human-readable error description
          example: The resource quota is not enough.
        request_id:
          type: string
          description: Tracing ID
          example: req-xxxx
        trace_id:
          type: string
          description: >-
            Server-side trace identifier for this request; quote it when
            reporting a problem.
        details:
          type: object
          description: Field-level error details
          additionalProperties: true
    ResourceSelection:
      allOf:
        - $ref: '#/components/schemas/PresetResourceSelection'
      description: |
        Resource values are selected by catalog product SKU
        (`GET /api/v2/products`); the service resolves the active entry from
        the product catalog.
    InitialBuildDefinition:
      type: object
      additionalProperties: false
      required:
        - source
      description: |
        Initial Build definition used only by the combined Template-create
        flow. A file context cannot be attached until the Template has a stable
        ID; use the split create/upload/start flow when files are required.
      properties:
        default_user:
          $ref: '#/components/schemas/TemplateDefaultUser'
        source:
          $ref: '#/components/schemas/BuildSource'
        commands:
          type: array
          maxItems: 100
          description: >
            Shell command strings executed sequentially during the Build. They
            may

            run as a non-root account with passwordless sudo: prefix privileged

            commands with `sudo`, and set ownership of files that the runtime

            account must use. To control the build identity explicitly, use a

            Dockerfile source with `USER` instructions, as in a regular
            Dockerfile.
          items:
            type: string
            minLength: 1
            maxLength: 8192
        envs:
          type: object
          maxProperties: 256
          additionalProperties:
            type: string
            maxLength: 32768
          description: Build-only environment variables; values are write-only.
        build_timeout_sec:
          type: integer
          minimum: 60
          maximum: 3600
          description: |
            Wall-clock budget for this Build in seconds. Omit or null to use the
            platform default (600). Allowed range: 60–3600. On expiry the Build
            is finalized as `error` with failure code `TemplateBuild.TimedOut`,
            its backing build in the selected IDC is cancelled, and its partial
            artifacts are reclaimed, best-effort.
        start_cmd:
          type: string
          minLength: 1
          maxLength: 8192
          description: Launch command applied when Sandboxes from this Template start.
    BuildStatus:
      type: string
      enum:
        - waiting
        - building
        - ready
        - error
      description: Normalized Template Build status.
    PresetResourceSelection:
      type: object
      additionalProperties: false
      required:
        - type
        - product
      properties:
        type:
          type: string
          enum:
            - preset
        product:
          type: string
          description: |
            Sandbox product specification id (catalog SKU, for example
            `gmi.sandbox.x-large`).
    TemplateDefaultUser:
      type: object
      additionalProperties: false
      required:
        - username
      description: >
        Runtime default identity for Sandboxes launched from this Build.

        Without it, Sandboxes run as `docker run` would: as the Dockerfile's
        final

        USER, else the image's USER, else root, in the final WORKDIR, else the

        image's, else `/`.

        Sandboxes run commands as a named account: an image USER given as a

        numeric uid (or uid:gid) needs a matching /etc/passwd entry in the
        image,

        otherwise the Build fails with a reason that names the USER. The group

        part is ignored.

        It is applied after all build commands and overrides the final
        Dockerfile

        USER at runtime; it does not change the identity of earlier build
        commands.


        Recommended setup for a custom account: create it in the Dockerfile,
        give

        it a working directory it can access, and pass its uid, for example

        `RUN useradd --uid 9999 --create-home --shell /bin/bash app`,

        `WORKDIR /home/app`, and `default_user: {username: app, uid: 9999}`.


        - default_user changes the identity only, not the working directory or
        its
          permissions. If the account cannot enter the final working directory,
          commands cannot start there and the Build may fail; declare an
          accessible WORKDIR to fix it.
        - With uid, the account must already exist with that UID and an existing
          home directory; otherwise the Build fails. The platform does not change
          UID, ownership, groups, or sudo privileges.
        - A non-root username without uid may be rejected with HTTP 422
          (Template.ProviderNotSupported); supply uid to avoid this. root may omit uid.
        - Invalid username, out-of-range uid, or root with a nonzero uid returns
          HTTP 400 (Parameter.Invalid).
        - A Build from a base template keeps the base template's user and
        working
          directory, as Docker FROM does; set default_user on the child Build to
          select another. Changing it requires a new Build.

        When omitted, the template's default runtime identity is used. A Build

        response reports the requested setting; an omitted uid stays omitted.
      properties:
        username:
          type: string
          minLength: 1
          maxLength: 32
          pattern: ^[a-z_][a-z0-9_-]{0,31}$
          example: app
        uid:
          type: integer
          format: int32
          minimum: 0
          maximum: 2147483647
          description: >-
            UID of the account. Recommended for non-root usernames. root only
            accepts 0.
          example: 9999
    BuildSource:
      oneOf:
        - $ref: '#/components/schemas/ImageSource'
        - $ref: '#/components/schemas/TemplateSource'
        - $ref: '#/components/schemas/DockerfileSource'
      discriminator:
        propertyName: type
        mapping:
          image: '#/components/schemas/ImageSource'
          template: '#/components/schemas/TemplateSource'
          dockerfile: '#/components/schemas/DockerfileSource'
      description: Manual Build source. Sandbox sources use the snapshot endpoint.
    ImageSource:
      type: object
      additionalProperties: false
      required:
        - type
        - image
      properties:
        type:
          type: string
          enum:
            - image
        image:
          type: string
          minLength: 1
          description: |
            OCI container image reference. The following distributions have
            been validated: Debian/Ubuntu, Fedora/CentOS Stream/Rocky Linux/
            AlmaLinux, Arch Linux, and Alpine Linux.
        registry_credential:
          $ref: '#/components/schemas/GeneralRegistryCredential'
    TemplateSource:
      type: object
      additionalProperties: false
      required:
        - type
        - template_id
      properties:
        type:
          type: string
          enum:
            - template
        template_id:
          type: string
          description: Parent GMI Template identifier in the same IDC.
        build_id:
          type: string
          description: |
            Optional parent Build identifier. When omitted, the parent's
            current successful Build is used.
    DockerfileSource:
      type: object
      additionalProperties: false
      required:
        - type
        - dockerfile
      properties:
        type:
          type: string
          enum:
            - dockerfile
        dockerfile:
          type: string
          minLength: 1
          maxLength: 262144
          description: >
            Raw Dockerfile text. Supported instructions: FROM (exactly one; no

            multi-stage), RUN, ENV, WORKDIR, USER, COPY/ADD, CMD/ENTRYPOINT;

            EXPOSE and VOLUME are skipped; anything else is rejected with 400.


            A trailing backslash continues an instruction on the next line;
            blank

            and comment lines inside a continuation are skipped.


            The Dockerfile's final USER is the runtime identity of Sandboxes
            unless

            `default_user` is set. A Build fails when that account cannot enter
            the

            final working directory; declare an accessible WORKDIR.


            COPY/ADD sources must reference an uploaded Template file as

            `COPY {{file:<file_id>}} /dest` — local paths and URLs are

            rejected, and at most one file may be referenced per build (its

            `file_id` must also be attached via `file_context`, with

            `file_context.destination` omitted).


            With a dockerfile source, the sibling `commands` and `envs` fields

            are forbidden: write RUN/ENV lines in the Dockerfile instead.

            CMD/ENTRYPOINT are extracted into the Build's start command; an

            explicit `start_cmd` takes precedence over them.


            ENV values are visible to subsequent build steps and are part of

            the sandbox runtime environment, as under `docker run`; a value

            passed as `env_vars` when creating a Sandbox overrides one of the

            same name. Do not put build-time secrets in ENV: build the Template

            from an image or template source and pass them in `envs`, which

            reach the build steps only.
    GeneralRegistryCredential:
      type: object
      additionalProperties: false
      required:
        - type
        - username
        - password
      description: >-
        A one-time registry credential used to pull the private image named by
        `image`. `username` and `password` are used only for this build request:
        they are never persisted and never returned in any response. The Build
        detail's `registry_authentication` reports only whether a credential was
        used and of what kind, never the username or password.
      properties:
        type:
          type: string
          enum:
            - general
        username:
          type: string
        password:
          type: string
          description: Can be a password or an access token.
  responses:
    BadRequest:
      description: >-
        Invalid request parameters. Two code families are used:
        `Request.InvalidParameter` for request parsing and format validation
        (unknown or malformed body fields, malformed IDs, invalid enum values,
        out-of-range paging) and `Parameter.Invalid` for business validation
        (for example a template or IDC that cannot be found, or a `timeout` over
        the limit). Unknown or invalid fields inside the `params` of `POST
        /sandboxes/{id}/actions` are reported as `Parameter.Invalid`. Other 400
        codes are specific to an operation, for example `Sandbox.SourceConflict`
        (both or neither of `template_id` and `snapshot_id`) and
        `Sandbox.IdempotentParameterMismatch` (an `Idempotency-Key` reused with
        different parameters). Both code families share the same HTTP status, so
        decide by the `code` value, not the status alone.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            code: Parameter.Invalid
            message: Invalid request parameters
            request_id: req-xxxx
    Unauthorized:
      description: Unauthenticated
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            code: Auth.Unauthorized
            message: Authentication required
            request_id: req-xxxx
    Forbidden:
      description: The caller cannot access the organization-scoped resource.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unsupported:
      description: |
        The request is valid but the selected IDC does not support
        the requested capability or resolved resource specification.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    QuotaExceeded:
      description: The configured or temporary resource quota would be exceeded.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    RequestCanceled:
      description: The caller canceled the current HTTP request.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            code: Request.Canceled
            message: Request canceled
            request_id: req-xxxx
    InternalError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            code: System.Internal
            message: An internal server error occurred
            request_id: req-xxxx
    UpstreamError:
      description: An upstream Sandbox service is unavailable or returned an error.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    RequestTimeout:
      description: The current HTTP request exceeded the control-plane processing deadline.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            code: Request.Timeout
            message: Request timed out
            request_id: req-xxxx
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >
        API Key or Access Token, always sent as `Authorization: Bearer <token>`.
        The gateway recognizes the token type automatically.

````

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