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

# Create an Instance with the Platform API

> Create a Namespace instance from Go, TypeScript, or plain HTTP.

An instance is a microVM on Linux, or a machine on macOS, that runs until a deadline you set.
A single `CreateInstance` call declares both the machine and the workload that runs on it, and returns while the instance boots.
Nothing is long-lived by default: when an instance reaches its deadline the platform sends `SIGTERM` and then shuts the machine down.

Workloads are declared in one of two fields.
`containers` runs OCI containers and is available on Linux.
`applications` runs processes directly on the host, which is how macOS workloads are declared.

## Getting Started

<Steps titleSize="h3">
  <Step title="Authenticate with Namespace">
    The SDKs have no login of their own. They read the credential written by `nsc login`, so [install the CLI](/docs/reference/cli/installation) and authenticate once:

    ```bash theme={null}
    nsc login
    ```

    <Info>
      Code that runs somewhere you can't log in, such as a script on another machine, can use a development token from [`nsc auth generate-dev-token`](/docs/reference/cli/auth-generate-dev-token) instead. The curl examples below send it as a bearer token. See [Build on your own workspace](/docs/platform/authentication/local-development#use-a-development-token-instead) to pass one to an SDK client.

      Inside a Namespace instance, the SDKs read the token from `NSC_TOKEN_FILE`, which is set automatically.
    </Info>
  </Step>

  <Step title="Add a client library">
    The Compute API is a Connect service, so a plain HTTP client works as well and needs no SDK.

    <CodeGroup>
      ```bash TypeScript theme={null}
      npm install @namespacelabs/sdk @bufbuild/protobuf
      ```

      ```bash Go theme={null}
      go get namespacelabs.dev/integrations
      ```

      ```bash curl theme={null}
      # Nothing to install. The curl examples use jq to read responses.
      jq --version
      ```
    </CodeGroup>
  </Step>

  <Step title="Create an instance">
    The example below requests a 2 vCPU Linux machine with 4 GB of memory, runs a command in a container, and waits for the instance to become ready.

    <CodeGroup>
      ```typescript TypeScript theme={null}
      import { loadDefaults } from "@namespacelabs/sdk/auth";
      import { createComputeClient } from "@namespacelabs/sdk/api/compute";
      import { timestampFromDate } from "@bufbuild/protobuf/wkt";

      const computeClient = createComputeClient({ tokenSource: await loadDefaults() });

      const created = await computeClient.compute.createInstance({
        shape: {
          virtualCpu: 2,
          memoryMegabytes: 4096,
          machineArch: "amd64",
          os: "linux",
        },
        documentedPurpose: "quickstart",
        deadline: timestampFromDate(new Date(Date.now() + 60 * 60 * 1000)),
        containers: [
          {
            name: "demo",
            imageRef: "busybox",
            args: ["sh", "-c", "echo hello from Namespace"],
          },
        ],
      });

      console.log(created.instanceUrl);

      await computeClient.compute.waitInstanceSync({ instanceId: created.metadata!.instanceId });
      ```

      ```go Go theme={null}
      package main

      import (
      	"context"
      	"fmt"
      	"log"
      	"time"

      	"google.golang.org/protobuf/types/known/timestamppb"
      	"namespacelabs.dev/integrations/api/compute"
      	"namespacelabs.dev/integrations/auth"
      	computepb "namespacelabs.dev/integrations/proto/namespace/cloud/compute/v1beta"
      )

      func main() {
      	ctx := context.Background()

      	token, err := auth.LoadDefaults()
      	if err != nil {
      		log.Fatal(err)
      	}

      	computeClient, err := compute.NewClient(ctx, token)
      	if err != nil {
      		log.Fatal(err)
      	}
      	defer computeClient.Close()

      	resp, err := computeClient.Compute.CreateInstance(ctx, &computepb.CreateInstanceRequest{
      		Shape: &computepb.InstanceShape{
      			VirtualCpu:      2,
      			MemoryMegabytes: 4 * 1024,
      			MachineArch:     "amd64",
      			Os:              "linux",
      		},
      		DocumentedPurpose: "quickstart",
      		Deadline:          timestamppb.New(time.Now().Add(1 * time.Hour)),
      		Containers: []*computepb.ContainerRequest{{
      			Name:     "demo",
      			ImageRef: "busybox",
      			Args:     []string{"sh", "-c", "echo hello from Namespace"},
      		}},
      	})
      	if err != nil {
      		log.Fatal(err)
      	}

      	fmt.Println(resp.InstanceUrl)

      	if _, err := computeClient.Compute.WaitInstanceSync(ctx, &computepb.WaitInstanceRequest{
      		InstanceId: resp.Metadata.InstanceId,
      	}); err != nil {
      		log.Fatal(err)
      	}
      }
      ```

      ```bash curl theme={null}
      NSC_TOKEN=$(nsc auth generate-dev-token)
      COMPUTE_API=https://us.compute.namespaceapis.com
      SERVICE=namespace.cloud.compute.v1beta.ComputeService

      # GNU date first, BSD/macOS date second.
      DEADLINE=$(date -u -d '+1 hour' +%Y-%m-%dT%H:%M:%SZ 2>/dev/null \
        || date -u -v+1H +%Y-%m-%dT%H:%M:%SZ)

      CREATED=$(curl -sS -X POST "$COMPUTE_API/$SERVICE/CreateInstance" \
        -H "Authorization: Bearer $NSC_TOKEN" \
        -H "Content-Type: application/json" \
        -d @- <<JSON
      {
        "shape": {
          "virtualCpu": 2,
          "memoryMegabytes": 4096,
          "machineArch": "amd64",
          "os": "linux"
        },
        "documentedPurpose": "quickstart",
        "deadline": "$DEADLINE",
        "containers": [
          {
            "name": "demo",
            "imageRef": "busybox",
            "args": ["sh", "-c", "echo hello from Namespace"]
          }
        ]
      }
      JSON
      )

      INSTANCE_ID=$(printf '%s' "$CREATED" | jq -r .metadata.instanceId)
      printf '%s' "$CREATED" | jq -r .instanceUrl

      curl -sS -X POST "$COMPUTE_API/$SERVICE/WaitInstanceSync" \
        -H "Authorization: Bearer $NSC_TOKEN" \
        -H "Content-Type: application/json" \
        -d "{\"instanceId\": \"$INSTANCE_ID\"}"
      ```
    </CodeGroup>

    `CreateInstance` returns as soon as the instance is accepted, before the workload is running.
    The response carries `metadata.instanceId` and a dashboard link in `instanceUrl`.
    `WaitInstanceSync` blocks until the instance is ready. `WaitInstance` streams boot progress instead.

    Requests over plain HTTP use the Connect protocol: `POST {baseUrl}/{service}/{method}` with a JSON body in protojson form, which is why the field names above are camelCase and enums are sent as strings.
    Server-streaming methods have unary `Sync` variants, so an HTTP client never has to stream.
  </Step>
</Steps>

## Next steps

<Columns cols={3}>
  <Card title="Configuration" icon="sliders-horizontal" href="/docs/platform/instances/configuration">
    Placement selectors, exported ports, volumes, macOS applications, and idempotent creation.
  </Card>

  <Card title="Run commands" icon="square-terminal" href="/docs/platform/instances/examples/run-commands">
    Execute a command inside a container with the CommandService.
  </Card>

  <Card title="SSH access" icon="key-round" href="/docs/platform/instances/examples/ssh">
    Fetch per-instance credentials and open an interactive session.
  </Card>
</Columns>

Working examples in Go and TypeScript are at [github.com/namespacelabs/examples](https://github.com/namespacelabs/examples).
The full API reference is at [buf.build/namespace/cloud](https://buf.build/namespace/cloud).


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