# Create a service

> POST /v1/services. Creates a service (decision 32): a Service URL https://<name>-<suffix>.ambi.run, an access policy and a target.

Source: https://legion.ambient.xyz/docs/api/services/create-service

`POST https://api.legion.ambient.xyz/v1/services`

Authenticate with an API key: `Authorization: Bearer $LEGION_API_KEY`.

Creates a service (decision 32): a Service URL `https://<name>-<suffix>.ambi.run`, an access policy and a target. The
`name` is unique only within the organization among its services that are not deleting or deleted (409
`service_name_taken`;: a name is free as soon as its service starts deleting, while the deleting service keeps
its own address); the `suffix` is 4 random lowercase
letters and digits (like the end of a rental's name) drawn at creation and never changed, so two organizations can
use the same name and an address cannot be guessed from a name. The URL is in the answer: always use it as given. `target.mode` `rental` ("On a rental"): a port of one of the organization's rentals, one replica, the renter's own
machine (a rental created with `serve` gets one by itself); the name defaults to the rental's name, with `-<port>`
when that is taken. `target.mode` `autoscaled` ("Autoscaled", serverless: scales to zero when idle): a catalog model (`catalog_id`) or, while custom images are on, an own `image` with `serve`; a private
image is read with the organization's registry credential exactly as `createRental` does: the one
whose host and path prefix best match the image, or `target.registry_credential_id` when given. The credential
used is stored on the service (`target.template.registry_credential_id`) and passed on every replica's
rental, so replicas never switch credentials; deleting a credential a service uses is refused
(409 `registry_credential_in_use`, naming the service). Defaults come from `getServiceDefaults`. hardware is cheapest that fits (constraints optional);
`monthly_spend_cap` is required: when this UTC month's estimated GPU spend reaches it, the service scales to zero
and answers 402 `spend_cap_reached` until the cap is raised or the month ends. At most 10 autoscaled services, 10
replicas per service and 20 across the organization (409 `replica_limit_exceeded`); 409 `no_matching_offers`
when no host fits now. `acknowledge_host_visibility` must be true the first time the organization autoscales. `access` defaults to `keys` ("API key required") for `autoscaled` and `public` for `rental`. With keys, `initial_key` (default name
"default", 90 days) is created and its secret is in the answer once (`Cache-Control: no-store`); a key with
`no_expiry` needs a fresh sign-in on a session (403 `step_up_required`). Protocol `comfyui` is not supported
(400 `service_kind_unsupported`). Needs `services.manage`; 20 creates an hour.

## Headers

- `Idempotency-Key`, string, required: Client-chosen key, unique per request intent, at most 255 characters.

## Request body

- `name`, string: The URL label. Required for mode autoscaled; for mode rental, default the rental's name (and port).
- `protocol`, ServiceProtocol: `openai`: an OpenAI-compatible API under `/v1/` (adds the quickstart, the model check and model-aware readiness). `http`: any HTTP service.
- `target`, ServiceTargetInput, required: Mode `rental`: `rental_id` and `port` (for a model the rental serves, its serve port). Mode `autoscaled`: `catalog_id` or (while custom images are on) `image` with `serve`, then optional `hardware` constraints and `scaling`. A private image is read with the organization's registry sign-in exactly as `createRental` does.
  - `mode`, ServiceMode, required: How a service runs. `rental` ("On a rental"): a port on one of your rentals, one replica, your machine. `autoscaled` ("Autoscaled"): Legion rents GPUs and runs 0 to N replicas with traffic (serverless: scales to zero when idle). Whether a service serves a model is said by `target.template` and `catalog_id`, not by the mode.
  - `rental_id`, string (uuid)
  - `port`, integer
  - `catalog_id`, string
  - `image`, string
  - `registry_credential_id`, string (uuid): . With `image`: the registry credential to read it with instead of the one that matches by host and path prefix. It must be the organization's and for the image's registry (422 `registry_credential_not_found`, `registry_credential_host_mismatch`). Not with `catalog_id` (400 `invalid_serve`).
  - `serve`, ServiceServeInput
    - `port`, integer, required
    - `model`, string: The served model name; required with protocol openai.
  - `health_path`, string: Probed by the router. Default /v1/models for openai, / for http.
  - `hardware`, ServiceHardware: Cheapest that fits (decisions 40 to 46): for each replica the autoscaler evaluates every eligible offer and every GPU count the model can split across (powers of two up to 8, at least the catalog entry's min_gpus), keeps the configurations the catalog fit check accepts and rents the cheapest total price per hour; ties go to the host with the higher Legion score. Every field is an optional constraint. Replicas may differ in hardware; a replacement re-runs the choice.
    - `strategy`, string
    - `max_price_per_replica_hour`, Money: The most one replica may cost an hour, all GPUs together, all-in. No replica starts above it; for interruptible it is also the bid, per GPU-hour each GPU's share (rounded down). Changed by updateService, it applies in place: no replica rolls, the next placement uses it, and each interruptible replica's bid moves to its share of the new ceiling at once, within the rental bid rules (at least the host's interruptible floor, at most its on-demand price, not under a preemption notice, a few changes an hour); a bid those rules refuse keeps its old value.
    - `gpu_models`, array of string: Only these GPU models (unordered: price decides). Absent: any.
    - `tier`, RentalTier: The kind of rental. `on_demand`: the host's `price_per_gpu_hour`; never stopped for another rental. `interruptible`: a bid on the host's spot auction, above the host's floor `interruptible_price_per_gpu_hour`, on GPUs no on-demand rental needs: an on-demand rental on the same host that needs its GPUs stops it, with the stop of the container (after a 5-minute notice, `preempt_at`, on hosts whose agent supports it; the notice is also written to `/workspace/.legion/preemption.json`), and it ends `stopped` with `stop_reason` `preempted` and its workspace kept (billed as storage, and started again by itself with `auto_resume`), or deleted when it chose `interruption_behavior` `delete`. The on-demand price is fixed for the rental. An interruptible rental is a bid on the host's spot auction: it pays the clearing price, which moves every 2 minutes between the host's floor and the rental's `max_price_per_gpu_hour`, and a higher bid can also stop it (`stop_reason` `outbid`) with the same notice.
    - `placement`, ServicePlacement: Where replicas run. `eligible_hosts` (the default), any host passing the service eligibility floor; `own_hosts`, only the organization's own hosts. A host can see the traffic it serves.
    - `min_gpu_memory_gb`, number: Own images: the GPU memory one replica needs, all GPUs together.
    - `gpu_counts`, array of integer: Own images: the GPU counts the model can run on (tensor parallel). Default 1, 2, 4, 8.
  - `scaling`, ServiceScalingInput: Omitted fields keep their default (`getServiceDefaults`) on create and their value on update. New fields may be added.
    - `min_replicas`, integer
    - `max_replicas`, integer: Legion never runs more, a rolling change's surge replica included.
    - `scale_to_zero`, boolean: With min_replicas 0: creating, resuming or changing the template boots one replica; once it is ready and idle_timeout_seconds pass without a request, it scales to zero.
    - `idle_timeout_seconds`, integer
    - `scale_down_delay_seconds`, integer: Load must stay below capacity this long before a replica is removed.
    - `warm_replicas`, integer: Replicas kept stopped (workspace kept, storage billed) after scale-down, restarted first.
    - `target_concurrency`, integer: Requests in flight per replica above which a replica is added.
    - `max_concurrency`, integer: Requests in flight per replica at most; more wait in the queue.
    - `queue_wait_threshold_ms`, integer: A replica is added when requests wait longer than this.
    - `request_timeout_seconds`, integer: The longest a request may take, streaming included.
  - `env`, array of EnvVarInput: . mode `autoscaled`: environment variables of every replica. See `EnvVarInput`.
    - `name`, string, required
    - `value`, string: Required except on an update that keeps a stored secret (see above).
    - `secret`, boolean
  - `model_settings`, ModelSettings: . mode `autoscaled` with `catalog_id`: model settings of every replica; they count toward the hardware each replica needs and the estimate.
  - `command`, CommandOverride: . mode `autoscaled` with `image`: the entrypoint override of every replica.
  - `args`, CommandOverride: . mode `autoscaled` with `image`: the CMD override of every replica.
- `access`, ServiceAccess: `public`: anyone (within `sources`) reaches the URL; the router limits requests per address. `keys`: callers send `Authorization: Bearer lek_...`; Legion checks the key and it never reaches the host. Keys can be created while public, so switching to keys needs no downtime. `sources` (CIDR ranges; empty for anyone) apply with either mode.
  - `mode`, ServiceAccessMode, required
  - `sources`, array of string
- `monthly_spend_cap`, Money: Required with mode autoscaled.
- `initial_key`, CreateServiceKeyRequest
  - `name`, string, required
  - `expires_in_days`, integer: Days until the key stops working. Absent is 90, unless `no_expiry`.
  - `no_expiry`, boolean: The key never expires. Needs a fresh sign-in on a session; refused together with `expires_in_days`.
  - `rate_limit_per_minute`, integer
- `acknowledge_host_visibility`, boolean: With mode autoscaled, required once per organization; it acknowledges that hosts can see the model, requests and responses they serve.
- `replica_web_terminal`, ServiceReplicaWebTerminalInput: . The web terminal of an autoscaled service's replicas (ServiceReplicaWebTerminal), as a merge patch: a field left out keeps its value. On createService, absent is off with `access` `organization`. On updateService it applies in place and never rolls replicas: `enabled` from the next replica the service starts (a rental's web terminal is fixed when it is created), `access` at once on every live and warm replica. Only the service's creator or an owner of the organization may change `access` (403 `terminal_access_forbidden`); anyone who may update the service may change `enabled`.
  - `enabled`, boolean: Allow the web terminal on the replicas; default false.
  - `access`, TerminalAccess: . Who may open the web terminal on a rental. `organization` (the default): every owner and member of the rental's organization with `rentals.manage`. `creator_and_owners`: only the person who created the rental (`created_by`) and the organization's owners. A rental with no `created_by` (created before) behaves as `organization` whatever this says. Set on `createRental`, changed with `updateRental` by the rental's creator or an owner. See CONTRACTS.md "Web terminal".

Example:

```json
{
  "name": "string",
  "protocol": "openai",
  "target": {
    "mode": "rental",
    "rental_id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
    "port": 1,
    "catalog_id": "string",
    "image": "string",
    "registry_credential_id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
    "serve": {
      "port": 1024,
      "model": "string"
    },
    "health_path": "string",
    "hardware": {
      "strategy": "cheapest_fit",
      "max_price_per_replica_hour": {
        "amount_minor": 250,
        "currency": "USD"
      },
      "gpu_models": [
        "string"
      ],
      "tier": "on_demand",
      "placement": "own_hosts",
      "min_gpu_memory_gb": 1,
      "gpu_counts": [
        1
      ]
    },
    "scaling": {
      "min_replicas": 0,
      "max_replicas": 1,
      "scale_to_zero": false,
      "idle_timeout_seconds": 60,
      "scale_down_delay_seconds": 60,
      "warm_replicas": 0,
      "target_concurrency": 1,
      "max_concurrency": 1,
      "queue_wait_threshold_ms": 100,
      "request_timeout_seconds": 10
    },
    "env": [
      {
        "name": "HF_TOKEN",
        "value": "string",
        "secret": false
      }
    ],
    "model_settings": {},
    "command": [
      "string"
    ],
    "args": [
      "string"
    ]
  },
  "access": {
    "mode": "public",
    "sources": [
      "203.0.113.0/24"
    ]
  },
  "monthly_spend_cap": {
    "amount_minor": 250,
    "currency": "USD"
  },
  "initial_key": {
    "name": "string",
    "expires_in_days": 7,
    "no_expiry": false,
    "rate_limit_per_minute": 1
  },
  "acknowledge_host_visibility": false,
  "replica_web_terminal": {
    "enabled": false,
    "access": "organization"
  }
}
```

## Responses

### 201

The service and its first key, with the secret shown once.

- `service`, Service, required
  - `id`, string (uuid), required
  - `name`, string, required: The service's name, unique within the organization; the start of the URL's label: https://<name>-<suffix>.ambi.run. A service made for a serve rental or an exposed port keeps that hostname as its address, which has no suffix.
  - `mode`, ServiceMode, required: How a service runs. `rental` ("On a rental"): a port on one of your rentals, one replica, your machine. `autoscaled` ("Autoscaled"): Legion rents GPUs and runs 0 to N replicas with traffic (serverless: scales to zero when idle). Whether a service serves a model is said by `target.template` and `catalog_id`, not by the mode.
  - `url`, string, required: https://<name>-<suffix>.ambi.run: the name and a random 4-character suffix drawn at creation, fixed for the service's life (the label is at most 63 characters, the name cut if needed). Use it as given; do not build it from the name. For openai the base URL is this plus /v1.
  - `protocol`, ServiceProtocol, required: `openai`: an OpenAI-compatible API under `/v1/` (adds the quickstart, the model check and model-aware readiness). `http`: any HTTP service.
  - `target`, ServiceTarget, required
    - `mode`, ServiceMode, required: How a service runs. `rental` ("On a rental"): a port on one of your rentals, one replica, your machine. `autoscaled` ("Autoscaled"): Legion rents GPUs and runs 0 to N replicas with traffic (serverless: scales to zero when idle). Whether a service serves a model is said by `target.template` and `catalog_id`, not by the mode.
    - `rental_id`, string (uuid): Mode rental: the rental.
    - `port`, integer: Mode rental: the rental's port.
    - `template`, ServiceTemplate
      - `catalog_id`, string
      - `image`, string, required
      - `port`, integer, required
      - `model`, string, required
      - `health_path`, string, required
      - `registry_credential_id`, string (uuid): . The registry credential an own private image is read with: resolved when the service is created or its image changes, and used by every replica, so replicas never switch credentials. Absent for a catalog model and for a public image.
      - `env`, array of EnvVar: . Each replica container's environment variables, secrets without their values. Absent when there are none.
      - `model_settings`, ModelSettings: . The model settings set on the template; absent when none are.
      - `command`, CommandOverride: . The entrypoint override; absent when the image's is used.
      - `args`, CommandOverride: . The CMD override; absent when the image's is used.
    - `hardware`, ServiceHardware: Cheapest that fits (decisions 40 to 46): for each replica the autoscaler evaluates every eligible offer and every GPU count the model can split across (powers of two up to 8, at least the catalog entry's min_gpus), keeps the configurations the catalog fit check accepts and rents the cheapest total price per hour; ties go to the host with the higher Legion score. Every field is an optional constraint. Replicas may differ in hardware; a replacement re-runs the choice.
      - `strategy`, string
      - `max_price_per_replica_hour`, Money: The most one replica may cost an hour, all GPUs together, all-in. No replica starts above it; for interruptible it is also the bid, per GPU-hour each GPU's share (rounded down). Changed by updateService, it applies in place: no replica rolls, the next placement uses it, and each interruptible replica's bid moves to its share of the new ceiling at once, within the rental bid rules (at least the host's interruptible floor, at most its on-demand price, not under a preemption notice, a few changes an hour); a bid those rules refuse keeps its old value.
      - `gpu_models`, array of string: Only these GPU models (unordered: price decides). Absent: any.
      - `tier`, RentalTier: The kind of rental. `on_demand`: the host's `price_per_gpu_hour`; never stopped for another rental. `interruptible`: a bid on the host's spot auction, above the host's floor `interruptible_price_per_gpu_hour`, on GPUs no on-demand rental needs: an on-demand rental on the same host that needs its GPUs stops it, with the stop of the container (after a 5-minute notice, `preempt_at`, on hosts whose agent supports it; the notice is also written to `/workspace/.legion/preemption.json`), and it ends `stopped` with `stop_reason` `preempted` and its workspace kept (billed as storage, and started again by itself with `auto_resume`), or deleted when it chose `interruption_behavior` `delete`. The on-demand price is fixed for the rental. An interruptible rental is a bid on the host's spot auction: it pays the clearing price, which moves every 2 minutes between the host's floor and the rental's `max_price_per_gpu_hour`, and a higher bid can also stop it (`stop_reason` `outbid`) with the same notice.
      - `placement`, ServicePlacement: Where replicas run. `eligible_hosts` (the default), any host passing the service eligibility floor; `own_hosts`, only the organization's own hosts. A host can see the traffic it serves.
      - `min_gpu_memory_gb`, number: Own images: the GPU memory one replica needs, all GPUs together.
      - `gpu_counts`, array of integer: Own images: the GPU counts the model can run on (tensor parallel). Default 1, 2, 4, 8.
    - `scaling`, ServiceScaling
      - `min_replicas`, integer, required
      - `max_replicas`, integer, required
      - `scale_to_zero`, boolean, required
      - `idle_timeout_seconds`, integer, required
      - `scale_down_delay_seconds`, integer, required
      - `warm_replicas`, integer, required
      - `target_concurrency`, integer, required
      - `max_concurrency`, integer, required
      - `queue_wait_threshold_ms`, integer, required
      - `request_timeout_seconds`, integer, required
  - `access`, ServiceAccess, required: `public`: anyone (within `sources`) reaches the URL; the router limits requests per address. `keys`: callers send `Authorization: Bearer lek_...`; Legion checks the key and it never reaches the host. Keys can be created while public, so switching to keys needs no downtime. `sources` (CIDR ranges; empty for anyone) apply with either mode.
    - `mode`, ServiceAccessMode, required
    - `sources`, array of string
  - `state`, ServiceState, required: What was decided. `capped` is set by the autoscaler when the monthly cap is reached.
  - `status`, ServiceStatus, required: What is happening, first match wins: `deleting`, `disabled` (Legion took it down), `paused`, `capped`, `suspended` (the organization is), `no_credit`, `scaled_to_zero`, `waiting_for_gpus` (no host of the chosen GPU types fits the price ceiling now), `starting` (a replica is starting and none is ready), `degraded` (`status_reason` says why, for example `start_failures`), `scaling`, `ready`. A service in mode `rental` follows its rental: `starting`, `ready`, or `stopped` while the rental is not running.
  - `status_reason`, string, required
  - `monthly_spend_cap`, Money, required: Required with mode autoscaled; optional for a rental.
  - `spend_this_month`, ServiceSpend, required
    - `month`, string, required: The UTC month, YYYY-MM.
    - `estimated`, Money, required: GPU time of the replicas this month at their all-in prices, the figure the cap is enforced on.
    - `cap`, Money, required: The monthly spend cap; null on a service in mode `rental` without one.
    - `alerted_pct`, integer, required: The highest cap alert sent this month. Alerts go to owners and the creator at the fixed thresholds 50, 80 and 100 percent.
  - `replicas`, ServiceReplicaCounts, required
    - `ready`, integer, required: Replicas the router sends requests to.
    - `provisioning`, integer, required: Replicas starting or loading.
    - `draining`, integer, required
    - `warm`, integer, required: Stopped replicas kept for a fast restart.
    - `desired`, integer, required: What the autoscaler last decided.
  - `cold_start_seconds`, integer, required: The median time a replica took to become ready; null before one did.
  - `last_request_at`, string (date-time), required
  - `created_at`, string (date-time), required
  - `created_by`, string (uuid), required
  - `revision`, integer (int64), required: Bumped on every change; send it back as `revision` to update safely.
  - `replica_web_terminal`, ServiceReplicaWebTerminal, required: . The Legion web terminal on the service's replicas, an autoscaled service's setting (a service in mode `rental` runs on a rental with its own `web_terminal` and `terminal_access`, and this does not change them). Each replica is a rental with `web_terminal` = `enabled` and `terminal_access` = `access`, created by the service's creator; its rental read names the service (`service_id`, `service_name`, `service_managed`). Off by default.
    - `enabled`, boolean, required: Whether replicas allow the web terminal. A change applies to the replicas started after it; a live or warm replica keeps the web terminal it was created with until it is replaced (a rental's `web_terminal` is fixed at creation), and a warm replica restarted keeps its own.
    - `access`, TerminalAccess, required: Who may open a replica's web terminal: `organization` (the default) or `creator_and_owners` (the service's creator and the organization's owners). A change applies at once to every live and warm replica, and to every replica after.
  - `keys`, array of ServiceKey: On getService only: the keys, as listServiceKeys' first page.
    - `id`, string (uuid), required
    - `kind`, ServiceKeyKind, required: `service`, an `lek_` key. `legacy_direct`, the `lsk_` key of a public model rental from before services; revoking it switches the service's access to keys.
    - `name`, string, required
    - `prefix`, string, required: The first 12 characters, `lek_` and 8 more (`lsk_` for a legacy direct key). Display only.
    - `status`, ServiceKeyStatus, required
    - `created_at`, string (date-time), required
    - `created_by`, string (uuid), required
    - `expires_at`, string (date-time), required
    - `last_used_at`, string (date-time), required: Updated at most once a minute.
    - `revoked_at`, string (date-time), required
    - `rate_limit_per_minute`, integer, required
    - `direct_url`, string, required: The direct address a legacy direct key opens.
  - `replica_list`, array of ServiceReplica: On getService only: live and warm replicas.
    - `rental_id`, string (uuid), required
    - `rental_name`, string, required
    - `phase`, ServiceReplicaPhase, required
    - `rental_state`, string, required
    - `ready`, boolean, required: The router's health probe passed in the last 15 seconds.
    - `ready_at`, string (date-time), required
    - `host`, ServiceReplicaHost, required
      - `name`, string, required
      - `country`, string, required
      - `gpu_model`, string, required
    - `gpu_count`, integer, required
    - `price_per_gpu_hour`, Money, required
      - `amount_minor`, integer (int64), required: Amount in minor units (cents for USD).
      - `currency`, MoneyCurrency, required: ISO 4217 currency code. Only USD is supported.
    - `tier`, RentalTier, required: The kind of rental. `on_demand`: the host's `price_per_gpu_hour`; never stopped for another rental. `interruptible`: a bid on the host's spot auction, above the host's floor `interruptible_price_per_gpu_hour`, on GPUs no on-demand rental needs: an on-demand rental on the same host that needs its GPUs stops it, with the stop of the container (after a 5-minute notice, `preempt_at`, on hosts whose agent supports it; the notice is also written to `/workspace/.legion/preemption.json`), and it ends `stopped` with `stop_reason` `preempted` and its workspace kept (billed as storage, and started again by itself with `auto_resume`), or deleted when it chose `interruption_behavior` `delete`. The on-demand price is fixed for the rental. An interruptible rental is a bid on the host's spot auction: it pays the clearing price, which moves every 2 minutes between the host's floor and the rental's `max_price_per_gpu_hour`, and a higher bid can also stop it (`stop_reason` `outbid`) with the same notice.
    - `in_flight`, integer: Requests in flight, as the router last reported.
    - `created_at`, string (date-time), required
    - `retire_reason`, string, required
    - `current_template`, boolean, required: False while a rolling change has not replaced this replica yet.
    - `startup`, Startup: . How far the replica's start has come: its rental's steps, after `finding_host` (done when the replica was placed), and `receiving_traffic` once the router's health probe passed (`ready_at`). Absent for a replica whose rental has no recorded steps (created before).
    - `failure`, ServeFailure: . Why the replica's model service last failed, when its host's agent said; also on a retired replica.
  - `startup`, Startup: . On getService only, while an autoscaled service places or starts a replica (`status` `starting`, `waiting_for_gpus` or `scaling`): while it waits for GPUs, `finding_host` current with the last placement's numbers (`facts.hosts_checked`, `hosts_busy`, `hosts_over_price`, `detail`); else the steps of the starting replica that is furthest behind. Absent otherwise; each replica carries its own on `replica_list`.
  - `usage`, ServiceUsageSummary
    - `requests_24h`, integer (int64), required
    - `errors_24h`, integer (int64), required
    - `replica_seconds_24h`, integer (int64), required
- `initial_key`, ServiceKeyCreated: The first key, its secret shown once. Absent when the service is created public, which makes no key.

Example:

```json
{
  "service": {
    "id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
    "name": "string",
    "mode": "rental",
    "url": "string",
    "protocol": "openai",
    "target": {
      "mode": "rental",
      "rental_id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
      "port": 0,
      "template": {
        "catalog_id": "string",
        "image": "string",
        "port": 0,
        "model": "string",
        "health_path": "string",
        "registry_credential_id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
        "env": [
          {
            "name": "HF_TOKEN",
            "secret": false,
            "value": "string"
          }
        ],
        "model_settings": {},
        "command": [
          "string"
        ],
        "args": [
          "string"
        ]
      },
      "hardware": {
        "strategy": "cheapest_fit",
        "max_price_per_replica_hour": {
          "amount_minor": 250,
          "currency": "USD"
        },
        "gpu_models": [
          "string"
        ],
        "tier": "on_demand",
        "placement": "own_hosts",
        "min_gpu_memory_gb": 1,
        "gpu_counts": [
          1
        ]
      },
      "scaling": {
        "min_replicas": 0,
        "max_replicas": 0,
        "scale_to_zero": false,
        "idle_timeout_seconds": 0,
        "scale_down_delay_seconds": 0,
        "warm_replicas": 0,
        "target_concurrency": 0,
        "max_concurrency": 0,
        "queue_wait_threshold_ms": 0,
        "request_timeout_seconds": 0
      }
    },
    "access": {
      "mode": "public",
      "sources": [
        "203.0.113.0/24"
      ]
    },
    "state": "active",
    "status": "ready",
    "status_reason": "string",
    "monthly_spend_cap": {
      "amount_minor": 250,
      "currency": "USD"
    },
    "spend_this_month": {
      "month": "2026-11",
      "estimated": {
        "amount_minor": 250,
        "currency": "USD"
      },
      "cap": {
        "amount_minor": 250,
        "currency": "USD"
      },
      "alerted_pct": 0
    },
    "replicas": {
      "ready": 0,
      "provisioning": 0,
      "draining": 0,
      "warm": 0,
      "desired": 0
    },
    "cold_start_seconds": 0,
    "last_request_at": "2026-10-15T12:00:00Z",
    "created_at": "2026-10-15T12:00:00Z",
    "created_by": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
    "revision": 0,
    "replica_web_terminal": {
      "enabled": false,
      "access": "organization"
    },
    "keys": [
      {
        "id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
        "kind": "service",
        "name": "string",
        "prefix": "string",
        "status": "active",
        "created_at": "2026-10-15T12:00:00Z",
        "created_by": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
        "expires_at": "2026-10-15T12:00:00Z",
        "last_used_at": "2026-10-15T12:00:00Z",
        "revoked_at": "2026-10-15T12:00:00Z",
        "rate_limit_per_minute": 0,
        "direct_url": "string"
      }
    ],
    "replica_list": [
      {
        "rental_id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
        "rental_name": "string",
        "phase": "active",
        "rental_state": "string",
        "ready": false,
        "ready_at": "2026-10-15T12:00:00Z",
        "host": {
          "name": "string",
          "country": "string",
          "gpu_model": "string"
        },
        "gpu_count": 0,
        "price_per_gpu_hour": {
          "amount_minor": 250,
          "currency": "USD"
        },
        "tier": "on_demand",
        "in_flight": 0,
        "created_at": "2026-10-15T12:00:00Z",
        "retire_reason": "string",
        "current_template": false,
        "startup": {
          "steps": []
        },
        "failure": {
          "reason": "string",
          "message": "string",
          "reported_at": "2026-10-15T12:00:00Z"
        }
      }
    ],
    "startup": {
      "steps": [
        {
          "step": "finding_host",
          "state": "done",
          "started_at": "2026-10-15T12:00:00Z",
          "ended_at": "2026-10-15T12:00:00Z",
          "progress": {
            "done_bytes": 0,
            "total_bytes": 0,
            "bytes_per_second": 0,
            "eta_seconds": 0,
            "fraction": 0,
            "reported_at": "2026-10-15T12:00:00Z"
          },
          "reason": "string",
          "detail": "string",
          "facts": {
            "gpu_model": "string",
            "gpu_count": 1,
            "country": "string",
            "hosts_checked": 0,
            "hosts_busy": 0,
            "hosts_over_price": 0,
            "cached": false,
            "items_done": 0,
            "items_total": 0,
            "load_fraction": 0,
            "gpu_memory_used_bytes": 0,
            "gpu_memory_total_bytes": 0,
            "kv_cache_bytes": 0,
            "compile_fraction": 0,
            "health_path": "string",
            "attempts": 0,
            "last_status_code": 0,
            "latency_ms": 0
          }
        }
      ]
    },
    "usage": {
      "requests_24h": 0,
      "errors_24h": 0,
      "replica_seconds_24h": 0
    }
  },
  "initial_key": {
    "key": {
      "id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
      "kind": "service",
      "name": "string",
      "prefix": "string",
      "status": "active",
      "created_at": "2026-10-15T12:00:00Z",
      "created_by": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
      "expires_at": "2026-10-15T12:00:00Z",
      "last_used_at": "2026-10-15T12:00:00Z",
      "revoked_at": "2026-10-15T12:00:00Z",
      "rate_limit_per_minute": 0,
      "direct_url": "string"
    },
    "secret": "string"
  }
}
```

### 400

The request is malformed or fails validation. An image reference that
is not a container image reference answers `invalid_image_reference`.

### 401

Missing, unknown, expired or revoked credentials.

### 402

The organization has no credit (`code` is `insufficient_credit`).

### 403

The caller lacks the permission this operation requires (`forbidden`),
or signed in without having joined an organization yet
(`no_organization`; `getOnboarding` and the invitation and
organization operations under it work), or could not sign in
(`email_unverified`, `account_conflict`, and `domain_not_allowed`). `not_invited` is no longer returned to
session tokens.

`access_not_approved`: a signed-in person who is not approved
for the beta yet. Every operation that takes a credential answers it to
them, except `getMe` and `joinMyWaitlist`; the problem carries
`access` (`waitlisted` or `not_requested`, and the email). Approved
means a member of an organization, holding a pending invitation, or Legion; an API key always belongs to a member.

`oauth_token_mcp_only`: the caller sent an OAuth access token (`lgo_`), which is accepted
only by `mcpMessage` and the tool calls it dispatches. Every other operation answers it, whatever
the token's scope. Use an API key or the Legion web app.

`org_suspended`: the caller's organization is suspended. Every operation that takes a
credential answers it, by session or API key, except `getMe` (which shows `org.suspended_at` and
`org.suspension_reason`) and the support operations under `/v1/support/`.

`terms_not_accepted`: an approved caller who has not accepted
the current version of the Terms of Use and the Acceptable Use Policy. Every operation that takes a credential answers it, except `getMe`,
`acceptLegalDocuments`, `joinMyWaitlist` and the wind-down operations
(`listRentals`, `stopRental`, `deleteRental`, `listHosts`,
`updateListing` with `listed` false, `removeHost`); the problem
carries `legal`. An API key acts for the person who created it, so it
is refused until that person accepts. Terminal
operations also return
`session_required` (called with an API key) and `step_up_required`
(neither a sign-in nor a step-up challenge within the step-up window).

### 409

The resource's current state does not allow the operation. `legal_versions_stale`: a legal document version sent is not the current one; the
problem's `legal` holds the current documents.

### 422

The Idempotency-Key was already used with a different request body.

### 429

Rate limited (`code` is `rate_limited`), or the organization asked the
pull-through mirror to copy in too many different tags or digests of one
repository today (`mirror_quota_exceeded`). Retry after the `Retry-After`
seconds.

### 500

An unexpected server error. Safe to retry.

### 503

A dependency is unavailable (`terminal_signing_unavailable`;
`image_registry_unavailable` when the image's registry did not answer in
time or failed; `secrets_unavailable` when secret variables cannot be
stored or read). Safe to retry.

## Errors

- 400 [`invalid_serve`](https://legion.ambient.xyz/docs/errors#invalid_serve)
- 400 [`service_kind_unsupported`](https://legion.ambient.xyz/docs/errors#service_kind_unsupported)
- 400 [`invalid_scaling`](https://legion.ambient.xyz/docs/errors#invalid_scaling)
- 400 [`invalid_hardware`](https://legion.ambient.xyz/docs/errors#invalid_hardware)
- 400 [`invalid_service_name`](https://legion.ambient.xyz/docs/errors#invalid_service_name)
- 400 [`invalid_spend_cap`](https://legion.ambient.xyz/docs/errors#invalid_spend_cap)
- 400 [`invalid_source`](https://legion.ambient.xyz/docs/errors#invalid_source)
- 400 [`host_visibility_not_acknowledged`](https://legion.ambient.xyz/docs/errors#host_visibility_not_acknowledged)
- 400 [`image_private`](https://legion.ambient.xyz/docs/errors#image_private)
- 400 [`registry_sign_in_rejected`](https://legion.ambient.xyz/docs/errors#registry_sign_in_rejected)
- 400 [`env_reserved`](https://legion.ambient.xyz/docs/errors#env_reserved)
- 400 [`invalid_env`](https://legion.ambient.xyz/docs/errors#invalid_env)
- 400 [`invalid_command`](https://legion.ambient.xyz/docs/errors#invalid_command)
- 400 [`override_not_allowed`](https://legion.ambient.xyz/docs/errors#override_not_allowed)
- 400 [`invalid_model_setting`](https://legion.ambient.xyz/docs/errors#invalid_model_setting)
- 402 [`insufficient_credit`](https://legion.ambient.xyz/docs/errors#insufficient_credit)
- 403 [`no_organization`](https://legion.ambient.xyz/docs/errors#no_organization)
- 403 [`custom_images_disabled`](https://legion.ambient.xyz/docs/errors#custom_images_disabled)
- 403 [`step_up_required`](https://legion.ambient.xyz/docs/errors#step_up_required)
- 403 [`service_unavailable`](https://legion.ambient.xyz/docs/errors#service_unavailable)
- 403 [`web_app_required`](https://legion.ambient.xyz/docs/errors#web_app_required)
- 409 [`service_name_taken`](https://legion.ambient.xyz/docs/errors#service_name_taken)
- 409 [`too_many_services`](https://legion.ambient.xyz/docs/errors#too_many_services)
- 409 [`replica_limit_exceeded`](https://legion.ambient.xyz/docs/errors#replica_limit_exceeded)
- 409 [`no_matching_offers`](https://legion.ambient.xyz/docs/errors#no_matching_offers)
- 409 [`rule_exists`](https://legion.ambient.xyz/docs/errors#rule_exists)
- 409 [`rental_not_live`](https://legion.ambient.xyz/docs/errors#rental_not_live)
- 409 [`host_unsupported`](https://legion.ambient.xyz/docs/errors#host_unsupported)
- 409 [`rental_unnamed`](https://legion.ambient.xyz/docs/errors#rental_unnamed)
- 409 [`too_many_rules`](https://legion.ambient.xyz/docs/errors#too_many_rules)
- 409 [`model_settings_unavailable`](https://legion.ambient.xyz/docs/errors#model_settings_unavailable)
- 422 [`idempotency_key_reused`](https://legion.ambient.xyz/docs/errors#idempotency_key_reused)
- 422 [`registry_credential_not_found`](https://legion.ambient.xyz/docs/errors#registry_credential_not_found)
- 422 [`registry_credential_host_mismatch`](https://legion.ambient.xyz/docs/errors#registry_credential_host_mismatch)
- 429 [`rate_limited`](https://legion.ambient.xyz/docs/errors#rate_limited)
- 503 [`secrets_unavailable`](https://legion.ambient.xyz/docs/errors#secrets_unavailable)

## Example request

```sh
curl -s -X POST "https://api.legion.ambient.xyz/v1/services" \
  -H "Authorization: Bearer $LEGION_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
  "name": "string",
  "protocol": "openai",
  "target": {
    "mode": "rental",
    "rental_id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
    "port": 1,
    "catalog_id": "string",
    "image": "string",
    "registry_credential_id": "0192f1a2-7c3d-7e4f-8a9b-0c1d2e3f4a5b",
    "serve": {
      "port": 1024,
      "model": "string"
    },
    "health_path": "string",
    "hardware": {
      "strategy": "cheapest_fit",
      "max_price_per_replica_hour": {
        "amount_minor": 250,
        "currency": "USD"
      },
      "gpu_models": [
        "string"
      ],
      "tier": "on_demand",
      "placement": "own_hosts",
      "min_gpu_memory_gb": 1,
      "gpu_counts": [
        1
      ]
    },
    "scaling": {
      "min_replicas": 0,
      "max_replicas": 1,
      "scale_to_zero": false,
      "idle_timeout_seconds": 60,
      "scale_down_delay_seconds": 60,
      "warm_replicas": 0,
      "target_concurrency": 1,
      "max_concurrency": 1,
      "queue_wait_threshold_ms": 100,
      "request_timeout_seconds": 10
    },
    "env": [
      {
        "name": "HF_TOKEN",
        "value": "string",
        "secret": false
      }
    ],
    "model_settings": {},
    "command": [
      "string"
    ],
    "args": [
      "string"
    ]
  },
  "access": {
    "mode": "public",
    "sources": [
      "203.0.113.0/24"
    ]
  },
  "monthly_spend_cap": {
    "amount_minor": 250,
    "currency": "USD"
  },
  "initial_key": {
    "name": "string",
    "expires_in_days": 7,
    "no_expiry": false,
    "rate_limit_per_minute": 1
  },
  "acknowledge_host_visibility": false,
  "replica_web_terminal": {
    "enabled": false,
    "access": "organization"
  }
}'
```
