# Apply a signed plan once.

POST https://services.leadconnectorhq.com/ai-builder-api/projects/{projectId}/changes/apply

Idempotent on `planId`: a second (or concurrent) apply of the same plan
returns the first apply's result without writing again (`queued` while
the first is still running). Apply re-checks the stored change against
what exists now; when it moved, the answer is 409 `change_plan_stale`
with a fix (plan again). An expired plan is 409 too. A `partial` result
stays open: applying the same plan again finishes only what is left.
Another location's or project's plan is 404.


## Authentication

Send `Authorization: Bearer <token>` using:

- **Sub-Account token: OAuth access token or Private Integration Token.** Scopes: `clientportal-ai.write`

## Parameters

### Header Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `Version` | string | Yes | The API version. |

### Path Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `projectId` | string | Yes | The project's id. |

## OpenAPI Specification

```json
{
  "openapi": "3.0.0",
  "info": {
    "title": "HighLevel API",
    "version": "v3"
  },
  "servers": [
    {
      "url": "https://services.leadconnectorhq.com"
    }
  ],
  "paths": {
    "/ai-builder-api/projects/{projectId}/changes/apply": {
      "post": {
        "summary": "Apply a signed plan once.",
        "operationId": "applyASignedPlanOnce",
        "description": "Idempotent on `planId`: a second (or concurrent) apply of the same plan\nreturns the first apply's result without writing again (`queued` while\nthe first is still running). Apply re-checks the stored change against\nwhat exists now; when it moved, the answer is 409 `change_plan_stale`\nwith a fix (plan again). An expired plan is 409 too. A `partial` result\nstays open: applying the same plan again finishes only what is left.\nAnother location's or project's plan is 404.\n",
        "parameters": [
          {
            "in": "path",
            "name": "projectId",
            "required": true,
            "schema": {
              "type": "string",
              "pattern": "^prj_[A-Za-z0-9_-]+$"
            },
            "description": "The project's id.",
            "example": "prj_5f0c2a3e"
          },
          {
            "name": "Version",
            "in": "header",
            "required": true,
            "description": "The API version.",
            "schema": {
              "type": "string",
              "enum": [
                "v3"
              ]
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ApplyChangeRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "What the apply did.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChangeApplyResult"
                },
                "example": {
                  "status": "applied",
                  "result": {
                    "enabled": [
                      "courses"
                    ],
                    "already": []
                  },
                  "links": {}
                }
              }
            }
          },
          "401": {
            "description": "No valid session."
          },
          "404": {
            "description": "No such plan for this project and location (`change_plan_not_found`).",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ApiError"
                }
              }
            }
          },
          "409": {
            "description": "The plan expired or is stale (`change_plan_stale`); the detail says how to fix it. kind=assets also answers 409 `customizer_image_not_uploaded` / `customizer_image_mismatch` until the declared bytes land; apply the same plan again after uploading.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ApiError"
                }
              }
            }
          },
          "422": {
            "description": "Request validation failed.",
            "content": {
              "application/problem+json": {
                "schema": {
                  "$ref": "#/components/schemas/ApiError"
                }
              }
            }
          }
        },
        "security": [
          {
            "bearer": [
              "clientportal-ai.write"
            ]
          }
        ]
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearer": {
        "type": "http",
        "scheme": "bearer",
        "description": "A sub-account access token: a Marketplace app's OAuth token or a Private Integration Token."
      }
    },
    "schemas": {
      "ApplyChangeRequest": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "planId"
        ],
        "properties": {
          "planId": {
            "type": "string",
            "maxLength": 2048,
            "pattern": "^cp1\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$",
            "description": "The `planId` POST …/changes/plan returned.",
            "example": "cp1.eyJwIjoicHJqXzVmMGMyYTNlIn0.c2lnbmF0dXJl"
          }
        },
        "title": "ApplyChangeRequest"
      },
      "ChangeApplyResult": {
        "type": "object",
        "additionalProperties": false,
        "required": [
          "status",
          "result",
          "links"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "applied",
              "queued",
              "partial"
            ],
            "description": "`applied`: done. `queued`: accepted and finishing in the background (or another apply of this plan is running). `partial`: some steps failed; apply the same plan again to finish.",
            "example": "applied"
          },
          "jobId": {
            "type": "string",
            "description": "The background operation, when one was queued (app-config operation id).",
            "example": "op_8d41c4b9"
          },
          "result": {
            "description": "Kind-specific outcome, e.g. records `{ok, created, reused, updated, deleted, skipped, failed}`; null while another apply runs.",
            "example": {
              "ok": true,
              "created": 2,
              "reused": 1
            }
          },
          "links": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
              "preview": {
                "type": "string",
                "format": "uri",
                "description": "A preview showing the change.",
                "example": "https://preview.example.com/my-portal"
              }
            },
            "description": "Where to see the result."
          }
        },
        "title": "ChangeApplyResult"
      },
      "ApiError": {
        "type": "object",
        "required": [
          "type",
          "title",
          "status",
          "code",
          "requestId"
        ],
        "properties": {
          "type": {
            "type": "string",
            "format": "uri",
            "example": "about:blank",
            "description": "A URI identifying the kind of error."
          },
          "title": {
            "type": "string",
            "example": "Request validation failed",
            "description": "Short summary of the kind of error."
          },
          "status": {
            "type": "integer",
            "minimum": 400,
            "maximum": 599,
            "example": 422,
            "description": "The HTTP status code."
          },
          "detail": {
            "type": "string",
            "example": "One or more fields are invalid.",
            "description": "What went wrong with this request."
          },
          "instance": {
            "type": "string",
            "example": "/api/v1/runs",
            "description": "The request path that failed."
          },
          "code": {
            "type": "string",
            "example": "validation_error",
            "description": "Stable, machine-readable error code."
          },
          "requestId": {
            "type": "string",
            "example": "req_01HXQ8Z6J9K2",
            "description": "The request's id, for support."
          },
          "fieldErrors": {
            "type": "array",
            "items": {
              "type": "object",
              "required": [
                "field",
                "code",
                "message"
              ],
              "properties": {
                "field": {
                  "type": "string",
                  "example": "prompt",
                  "description": "The invalid field, as a dotted path."
                },
                "code": {
                  "type": "string",
                  "example": "required",
                  "description": "Machine-readable reason."
                },
                "message": {
                  "type": "string",
                  "example": "Prompt is required.",
                  "description": "Human-readable reason."
                }
              },
              "title": "FieldError"
            },
            "description": "One entry per invalid field, when the request body was invalid.",
            "example": [
              {
                "field": "name",
                "code": "too_long",
                "message": "name must be at most 120 characters"
              }
            ]
          }
        },
        "title": "ApiError"
      }
    }
  }
}
```

## Code Examples

**cURL**

```bash
curl -L -X POST 'https://services.leadconnectorhq.com/ai-builder-api/projects/<projectId>/changes/apply' \
  -H 'Authorization: Bearer <TOKEN>' \
  -H 'Version: v3' \
  -H 'Content-Type: application/json' \
  --data-raw '{
  "planId": "cp1.eyJwIjoicHJqXzVmMGMyYTNlIn0.c2lnbmF0dXJl"
}'
```

**Node.js**

```javascript
const options = {
  method: 'POST',
  headers: {
    Authorization: 'Bearer <TOKEN>',
    Version: 'v3',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
      "planId": "cp1.eyJwIjoicHJqXzVmMGMyYTNlIn0.c2lnbmF0dXJl"
  })
};

try {
  const response = await fetch('https://services.leadconnectorhq.com/ai-builder-api/projects/<projectId>/changes/apply', options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

**Python**

```python
import requests

url = "https://services.leadconnectorhq.com/ai-builder-api/projects/{projectId}/changes/apply"

headers = {
    "Authorization": "Bearer <TOKEN>",
    "Version": "v3"
}

payload = {
    "planId": "cp1.eyJwIjoicHJqXzVmMGMyYTNlIn0.c2lnbmF0dXJl"
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
```

**PHP**

```php
<?php
$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => 'https://services.leadconnectorhq.com/ai-builder-api/projects/<projectId>/changes/apply',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_HTTPHEADER => [
    'Authorization: Bearer <TOKEN>',
    'Version: v3',
    'Content-Type: application/json',
  ],
  CURLOPT_POSTFIELDS => '{
  "planId": "cp1.eyJwIjoicHJqXzVmMGMyYTNlIn0.c2lnbmF0dXJl"
}',
]);

$response = curl_exec($curl);
curl_close($curl);
echo $response;
```

**Java**

```java
HttpResponse<String> response = Unirest
  .post("https://services.leadconnectorhq.com/ai-builder-api/projects/<projectId>/changes/apply")
  .header("Authorization", "Bearer <TOKEN>")
  .header("Version", "v3")
  .header("Content-Type", "application/json")
  .body("{\"planId\":\"cp1.eyJwIjoicHJqXzVmMGMyYTNlIn0.c2lnbmF0dXJl\"}")
  .asString();
```

**Go**

```go
package main

import (
  "fmt"
  "net/http"
  "io"
  "strings"
)

func main() {
  url := "https://services.leadconnectorhq.com/ai-builder-api/projects/<projectId>/changes/apply"
  payload := strings.NewReader(`{
  "planId": "cp1.eyJwIjoicHJqXzVmMGMyYTNlIn0.c2lnbmF0dXJl"
}`)
  req, _ := http.NewRequest("POST", url, payload)
  req.Header.Add("Authorization", "Bearer <TOKEN>")
  req.Header.Add("Version", "v3")

  res, _ := http.DefaultClient.Do(req)
  defer res.Body.Close()
  body, _ := io.ReadAll(res.Body)
  fmt.Println(string(body))
}
```

**Ruby**

```ruby
require 'uri'
require 'net/http'

url = URI("https://services.leadconnectorhq.com/ai-builder-api/projects/<projectId>/changes/apply")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = "Bearer <TOKEN>"
request["Version"] = "v3"
request["Content-Type"] = "application/json"
request.body = '{
  "planId": "cp1.eyJwIjoicHJqXzVmMGMyYTNlIn0.c2lnbmF0dXJl"
}'

response = http.request(request)
puts response.read_body
```

**PowerShell**

```powershell
$headers = @{
  "Authorization" = "Bearer <TOKEN>"
  "Version" = "v3"
}

$body = '{
  "planId": "cp1.eyJwIjoicHJqXzVmMGMyYTNlIn0.c2lnbmF0dXJl"
}'

$response = Invoke-RestMethod -Uri 'https://services.leadconnectorhq.com/ai-builder-api/projects/<projectId>/changes/apply' -Method 'POST' -Headers $headers -Body $body -ContentType 'application/json'
$response | ConvertTo-Json
```
