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

# 推广帖子

> 把自然发布的 Instagram 帖子转为付费广告：设置定位、总预算或广告活动预算、排期与广告目标，可推广到现有广告活动，并需满足 Meta 付款方式要求。

推广一条现有的 Instagram 帖子以创建广告。
此端点允许您使用自定义定位、预算和排期参数，将自然发布的帖子转换为付费广告。

<ul>
  <li>
    预算和出价金额使用广告账户的币种。最多保留两位小数；对于 Meta 仅接受整数单位的币种（CLP、COP、CRC、HUF、IDR、ISK、JPY、KRW、PYG、TWD 和 VND），请使用整数。
  </li>

  <li>为满足 Instagram 的要求，广告必须至少投放 30 小时。</li>

  <li>
    您可以使用 [兴趣端点](https://www.ayrshare.com/docs/apis/ads/instagram/get-ad-interests.md) 来查找用于定位的兴趣 ID。
  </li>

  <li>Instagram 审核并批准推广帖子最多可能需要 24 小时。</li>

  <li>
    如果直接使用 `socialPostId`（而非 Ayrshare 的 `postId`），请确保它是有效的 Instagram 帖子 ID。
  </li>

  <li>
    如果在 Facebook 创建活动之后（在创意、广告组或广告步骤）推广失败，
    我们会尝试删除该活动。如果删除也失败，空活动会保留在您的广告账户中。
    您可以在广告管理工具（Ads Manager）中找到并删除它。
  </li>
</ul>

> [!NOTE]
>
> 满足以下两个条件之前，Meta 会拒绝创建广告：
>
> * **广告账户已添加付款方式。** 在 Meta 的[账单和付款](https://business.facebook.com/billing_hub/payment_settings/?placement=ads_manager)中添加付款方式，并将其关联到您在 `accountId` 中发送的广告账户。仅保存在商务资产组合中的付款方式是不够的。
> * **已开启个性化广告（欧盟、欧洲经济区和瑞士）。** 如果与您的 Facebook 主页关联的 Facebook 或 Instagram 账户的所有者选择了查看个性化程度较低的广告，或订阅了无广告的 Meta 服务，Meta 将不允许该账户及该主页投放广告。所有者可以在账户中心 → 广告偏好 → 广告体验中改回个性化广告或取消订阅。[了解详情](https://www.facebook.com/business/help/1563729837497242)。

### 广告目标

每条广告都必须设置一个目标（goal）。目标决定了广告将如何针对展示进行优化。

<ul>
  <li>
    `engagement`（互动）：该目标旨在提升互动，同时确保广告触达尽可能多的独立用户。
    它在曝光度与互动之间取得平衡，把广告展示给尽可能多可能与之互动的不同用户。
  </li>

  <li>
    `interactions`（互动动作）：旨在增加广告的互动，例如点赞、评论和分享。
    Instagram 会优先将广告展示给最有可能与之互动的用户。
  </li>

  <li>
    `awareness_views`（品牌认知—展示）：通过最大化广告的展示次数来提升品牌认知。
    它会在预算范围内优先尽可能多次地展示广告，而不考虑独立触达。
  </li>

  <li>
    `awareness_audience`（品牌认知—受众）：通过最大化看到广告的独立用户数量来增强品牌认知。
    它确保广告触达尽可能多的不同用户，并最大化独立受众规模，而不是对同一受众多次展示。
  </li>
</ul>

> [!NOTE]
>
> Instagram 广告需要一个通过 Facebook 连接的 Instagram Business 账户、一个关联的 Facebook 主页，以及 `ads_management` 权限。请通过 Facebook 重新关联以授予此权限。使用 Instagram Login 连接的账户无法使用这些广告端点。媒体 ID 和 Instagram 账户 ID 会从您已关联的账户中解析得出；请勿发送 `instagram_user_id`。

`socialPostId` 选择器也接受 Instagram 专用的别名 `igPostId`。`fbPostId` 仅适用于 Facebook。成功的响应包含 `platform: "instagram"`、`socialPostId` 和 `igPostId`。

## 请求头参数

**Authorization** `string` *required*

[API Key](https://www.ayrshare.com/docs/apis/overview.md#authorization) of the Primary Profile.

Format: `Authorization: Bearer API_KEY`
**Profile-Key** `string`

[Profile Key](https://www.ayrshare.com/docs/apis/overview.md#profile-key-format) of a User Profile.

Format: `Profile-Key: PROFILE_KEY`

## 请求体参数

**idempotencyKey** `string`

此次推广请求的唯一非空键。使用相同的键重试相同的载荷可避免创建重复广告。使用相同的键但载荷不同，或用于 Facebook 推广，会返回 HTTP 409。在其他任何平台上，相同的键会创建一个独立的推广。仍在处理中的请求同样会返回 409；预留不可用时会返回 503 且不会创建广告。

**adSetBudgetSharingEnabled** `boolean` (default: false)

允许 Meta 在活动内的各广告集之间共享预算。

**accountId** `string` *required*

用于推广该帖子的 Instagram 广告账户 ID。可以从 [广告账户端点](https://www.ayrshare.com/docs/apis/ads/instagram/get-ad-accounts.md) 获取账户 ID。

**adName** `string` *required*

您的广告名称（显示在 Instagram Ad Manager 中），格式为 `{adName} - {postId or socialPostId} - {current date}`。如果您发送 `idempotencyKey`，名称末尾还会附加 ` - {request reference}`，这是一个简短的请求标识，同一密钥的标识保持不变。

**bidAmount** `number` *required*

最高出价金额，以广告账户的币种计，为正数。

**budget** `number` *required*

每日预算，以广告账户的币种计，为正数。Meta 可能会针对您的账户和目标强制执行最低限额。

**socialPostId** `string`

要推广的帖子的 [Instagram 社交帖子 ID](https://www.ayrshare.com/docs/apis/overview.md#social-post-id)，可用于以直接在 Instagram 上创建的帖子来创建广告。
这是 [Instagram 上帖子](https://www.ayrshare.com/docs/apis/history/history-platform.md) 的 ID，而不是 Ayrshare 的 ID。如果未设置 `postId`，则该参数必填。

**goal** `string` (default: engagement)

广告的目标。可选值：`engagement`、`interactions`、`awareness_views` 和
`awareness_audience`。详见上文 [广告目标详细说明](https://www.ayrshare.com/docs/apis/ads/instagram/boost-post.md#ad-goals)。

**locations** `object`

使用 `{"countries": ["US", "CA"]}` 及 [国家代码](https://www.ayrshare.com/docs/iso-codes/country.md) 来定位目标国家。您也可以提供 `regions` 和 `cities` 数组；详见 [地区](https://www.ayrshare.com/docs/apis/ads/instagram/get-ad-regions.md) 和 [城市](https://www.ayrshare.com/docs/apis/ads/instagram/get-ad-cities.md)。未指定任何国家、地区或城市的对象（例如 `{}`）会被拒绝并返回代码 `101`；如需定位美国，请省略 `locations`。

**postId** `string`

要推广的帖子的 [Ayrshare 帖子 ID](https://www.ayrshare.com/docs/apis/overview.md#ayrshare-post-id)。如果未设置 `socialPostId`，则该参数必填。

**status** `string` (default: active)

广告的状态。可选值：`active` 和 `paused`。

之后可以使用 [更新广告端点](https://www.ayrshare.com/docs/apis/ads/instagram/put-ad-update.md) 修改广告状态。

**tracking** `object`

使用 Meta Pixel 跟踪广告。

**子属性**

**pixelId** `number` *required*

用于跟踪广告的 Meta Pixel ID。

```json theme={"system"}
{
 "pixelId": 1234567890
}
```

**urlTags** `array`

向广告 URL 添加 UTM 标签。

```json theme={"system"}
{
  "urlTags": ["utm_source=ayrshare", "utm_medium=social", "utm_campaign=ayrshare-social"]
}
```

例如，如果链接 URL 为 `https://www.mysite.com/my-post`，添加的 URL 标签为：

`utm_source=ayrshare`、`utm_medium=social` 和 `utm_campaign=ayrshare-social`。

那么广告 URL 将为：
`https://www.mysite.com/my-post?utm_source=ayrshare&utm_medium=social&utm_campaign=ayrshare-social`。

**specialAdCategories** `array`

Meta 要求属于 [特殊广告类别](https://www.facebook.com/business/help/298000447747885?helpref=faq_content) 的广告主必须自行标识其活动类别。

如果您的业务属于其中之一，在推广帖子时必须选择相应的类别。

支持以下取值：

<ul>
  <li>
    `housing`（住房）：推广或直接链接到住房机会或相关服务的广告，包括但不限于房屋或公寓的
    出售/出租信息、房主保险、按揭保险、按揭贷款、房屋维修以及房屋净值或估价服务。
  </li>

  <li>
    `financial_product_services`（金融产品与服务）：推广或直接链接到金融产品与服务优惠
    （包括信贷）的广告。
  </li>

  <li>
    `employment`（就业）：推广或直接链接到就业机会的广告，包括但不限于兼职或全职工作、
    实习或专业认证项目。此类别还包括对招聘网站或招聘会、招聘聚合服务，或详述公司福利的广告
    （无论是否有具体的职位提供）。
  </li>

  <li>
    `issues_elections_politics`（社会议题、选举或政治）：由候选人、政治人物、政党，或代表他们，
    或与其相关的广告，或倡导选举结果的广告。这也包括与任何选举、公投或投票倡议相关的广告，
    包括"号召投票"的选举宣传。以及在投放地被视为政治广告或涉及社会议题的广告。若选择社会议题、
    选举或政治，则必须选择投放这些广告的国家/地区。您必须已获得在该指定国家/地区投放社会议题、
    选举或政治相关广告的授权。
  </li>
</ul>

Meta 还需要知道特殊类别广告投放的国家/地区。Ayrshare 从 `locations` 中获取这些国家/地区：您列出的国家/地区，以及每个地区和城市所属的国家/地区。因此，定位英国城市的 `housing` 推广会自动设置为英国，无需在请求中添加任何内容。如果未提供 `locations`，广告将在美国投放，活动也会设置为美国。

Meta 还为这些类别设定了每个城市周围的最小半径。一个半径为 17 公里的英国城市被拒绝并返回 `#2909039`，该错误要求至少 25 公里（15 英里），因此请使用 25 公里或以上。

> [!WARNING]
>
> Meta 要求广告主必须正确标识其活动类别。
> Meta 会使用人工审核和机器学习来识别此类广告。
> 如果您向我们发送了错误的 `specialAdCategories`，您的广告可能会被暂停，直到活动被调整为止。

**dsaBeneficiary** `string`

广告的受益人或受益组织。需与 `dsaPayor` 一同设置。可使用 [DSA 建议端点](https://www.ayrshare.com/docs/apis/ads/instagram/get-dsa-recommendations.md) 获取建议。

**dsaPayor** `string`

为广告付款的个人或组织。需与 `dsaBeneficiary` 一同设置。

**endDate** `string`

ISO 8601 格式的结束日期和时间（必须至少在开始时间后 30 小时），例如 `2025-03-01T00:00:00Z`。

如果未设置，广告将无限期运行，结束日期为 `ongoing`（进行中）。

**excludedLocations** `object`

使用与 `locations` 相同的 `countries`、`regions` 和 `cities` 结构来排除位置。

**gender** `string` (default: all)

受众性别。可选值：`all`（全部）、`male`（男性）、`female`（女性）。

**interests** `array`

广告的目标兴趣，作为 Instagram [兴趣 ID](https://www.ayrshare.com/docs/apis/ads/instagram/get-ad-interests.md) 的数组。

**maxAge** `number` (default: 65)

广告定位的最大年龄（默认：65）。

**minAge** `number` (default: 18)

广告定位的最小年龄（默认：18）。

**startDate** `string`

ISO 8601 格式的开始日期和时间，例如 `2025-03-01T00:00:00Z`。

如果未设置，广告将立即开始投放。

请将示例中的 ID 替换为您自己的 ID。将 `startDate` 和 `endDate` 设置为您预期的排期；示例中的日期仅供说明。

## 总预算

上面的请求体在广告集上设置每日预算。如需使用总预算，请改为发送推广请求体的嵌套格式。

在嵌套格式中，`accountId`、`postId`（或用 `socialPostId` 代替 `igPostId`）、`goal`、`status` 和 `callToAction` 保留在顶层。三个对象取代扁平格式中的预算、日期和定位字段：`budget`、`schedule`（`start`、`end`）和 `targeting`（`locations`、`excludedLocations`、`ageMin`、`ageMax`、`genders`、`interests`）。其余字段 `adName`、`bidAmount`、`specialAdCategories`、`adSetBudgetSharingEnabled`、`link`、`tracking`、`urlTags`、`dsaBeneficiary` 和 `dsaPayor` 移至 `platformOptions.instagram` 下。

```json theme={"system"}
{
  "accountId": "123456789",
  "postId": "Ut1fWU6XkqkMayHGnJZ",
  "goal": "engagement",
  "budget": { "amount": 50, "type": "lifetime" },
  "schedule": { "start": "2026-11-01T00:00:00Z", "end": "2026-11-08T00:00:00Z" },
  "targeting": { "ageMin": 25, "ageMax": 45, "locations": { "countries": ["US"] } },
  "platformOptions": { "instagram": { "adName": "November boost", "bidAmount": 2 } }
}
```

* `budget.type`：`daily`（默认值）或 `lifetime`。总预算在开始日期和结束日期之间花费，因此需要 `schedule.end`。如果没有结束日期，请求会被拒绝，并返回 `400` 和 `code: 101`。Meta 的广告集预算共享仅适用于每日预算，因此设置了 `adSetBudgetSharingEnabled: true` 的总预算同样会被拒绝，并返回 `code: 101`。

对于总预算，响应中会额外包含 `budgetType: "lifetime"`。每日预算不会返回 `budgetType`，因此缺少该字段时请视为 `daily`。

## 广告活动预算

如需将预算设置在广告活动上而不是广告集上，请在上文所示的嵌套格式中发送 `budget.level: "campaign"`。此时广告集本身没有预算。该设置适用于每日预算和总预算。

```json theme={"system"}
{
  "accountId": "123456789",
  "postId": "Ut1fWU6XkqkMayHGnJZ",
  "goal": "engagement",
  "budget": { "amount": 50, "type": "lifetime", "level": "campaign" },
  "schedule": { "start": "2026-11-01T00:00:00Z", "end": "2026-11-08T00:00:00Z" },
  "platformOptions": { "instagram": { "adName": "November boost", "bidAmount": 2 } }
}
```

* `budget.level`：`adSet`（默认值）或 `campaign`。广告活动预算不能与 `adSetBudgetSharingEnabled` 一起使用。同时发送两者会被拒绝，并返回 `400` 和 `code: 101`。
* 对于广告活动预算，响应中会额外包含 `budgetLevel: "campaign"`。广告集预算不会返回 `budgetLevel`，因此缺少该字段时请视为 `adSet`。
* 在[历史记录](https://www.ayrshare.com/docs/apis/ads/instagram/get-ad-history.md)中，对于使用每日广告活动预算的广告，`budgetDaily` 显示该广告活动的每日预算。如果多个广告共享同一个广告活动预算，每个广告都会显示整个广告活动的预算，而非其所占的份额。历史记录不会显示总预算，无论是广告活动还是广告集上的总预算。一旦广告活动的总预算花完，在下一次夜间更新后，该广告活动中的每个广告都会显示 `deliveryStatus: "COMPLETED"`，包括已排期或正在审核中的广告。被拒绝的广告仍保持 `REJECTED`。

## 推广到现有广告活动或广告集

默认情况下，每次推广都会创建自己的广告活动、广告集和广告。如需将推广添加到您已在 Meta 中运行的广告活动或广告集，请使用嵌套格式并发送 `attachTo`。

* `attachTo.campaignId`：推广会在该广告活动中创建新的广告集和广告。照常发送 `budget`、`targeting` 和 `bidAmount`：它们会应用于新的广告集。
* `attachTo.adSetId`：推广仅在该广告集中创建广告。同时还需发送 `attachTo.campaignId`，即该广告集所属的广告活动。请省略 `budget`、`targeting` 和 `platformOptions.instagram.bidAmount`：广告集会保留其自身的设置。发送其中任何一个都会返回 `400` 和 `code: 101`。

```json theme={"system"}
{
  "accountId": "123456789",
  "postId": "Ut1fWU6XkqkMayHGnJZ",
  "goal": "engagement",
  "attachTo": { "campaignId": "120210000000000001", "adSetId": "120210000000000002" },
  "platformOptions": { "instagram": { "adName": "November boost" } }
}
```

* 广告活动或广告集必须位于 `accountId` 指定的广告账户中，且不能属于其他用户的推广。否则请求会返回 `400`。此外，Instagram 推广不能附加到由 Facebook 推广创建的广告活动，反之亦然。
* `attachTo` 不能与 `budget.level: "campaign"`、`specialAdCategories` 或 `adSetBudgetSharingEnabled` 一起使用，这些设置用于新建的广告活动。发送它们会返回 `code: 101`。
* 暂停或激活推广只会改变推广所创建的内容：广告，以及由推广创建的广告集。您在 `attachTo` 中指定的广告活动或广告集会保留其自身的状态。广告仅在其上层的广告活动和广告集都处于活跃状态时投放。当 Ayrshare 暂停您的广告时（例如删除某个用户资料时）也同样适用。
* 如果推广失败，`attachTo` 中指定的广告活动或广告集绝不会被删除。
* 如果您附加的广告集位于持有预算的广告活动中（即广告活动预算），[历史记录](https://www.ayrshare.com/docs/apis/ads/instagram/get-ad-history.md) 会像报告任何使用广告活动预算的广告一样报告该推广：`budgetDaily` 显示整个广告活动的预算，而非该推广所占的份额；并且一旦广告活动的总预算花完，在下一次夜间更新后，Ayrshare 在该广告活动中跟踪的每个广告都会显示 `deliveryStatus: "COMPLETED"`，包括已排期或正在审核中的广告。被拒绝的广告仍保持 `REJECTED`。

## 打开对话而非链接

推广的按钮可以打开与您企业的聊天，而非网页。请使用嵌套格式发送 `callToAction.destination`，并省略 `callToAction.link`。

| `destination` | 打开 | `callToAction.type` |
| - | - | - |
| `messenger` | Messenger | `MESSAGE_PAGE` |
| `whatsapp` | WhatsApp | `WHATSAPP_MESSAGE` |
| `instagramDm` | Instagram Direct | `INSTAGRAM_MESSAGE` |

```json theme={"system"}
{
  "accountId": "123456789",
  "postId": "Ut1fWU6XkqkMayHGnJZ",
  "goal": "engagement",
  "budget": { "amount": 20 },
  "callToAction": { "type": "WHATSAPP_MESSAGE", "destination": "whatsapp" },
  "platformOptions": { "instagram": { "adName": "Chat with us", "bidAmount": 2 } }
}
```

* 请使用 `engagement` 或 `interactions` [广告目标](https://www.ayrshare.com/docs/apis/ads/instagram/boost-post.md#ad-goals)。此时广告会针对对话进行优化：Meta 会将其展示给可能发起聊天的用户。其他目标会返回 `400` 及 `code: 101`。
* `callToAction.type` 必须与目标对应，如上表所示。接受任意大小写。
* `callToAction.link` 和 `callToAction.linkTitle` 不能与 `destination` 一起发送，因为按钮打开的是聊天而非页面。不使用 `destination` 时，`link` 仍为必填项。
* 用户会向与您的用户资料关联的账户发送消息。对于 `whatsapp`，其 Facebook Page 必须已在 Meta 中连接 WhatsApp Business 号码。
* `destination` 不能与 `attachTo.adSetId` 一起使用：现有广告集会保留其已有的目标。使用 `attachTo.campaignId` 时，该广告活动必须具有 Meta 的 `OUTCOME_ENGAGEMENT` 目标；否则请求会返回 `400` 及 `code: 101`。
* 响应以及[已推广广告端点](https://www.ayrshare.com/docs/apis/ads/instagram/get-boosted-ads.md)会返回包含 `destination` 的 `callToAction`。Meta 为这两种目标存储相同的设置，因此使用 `interactions` 推广的聊天按钮在从 Meta 读回广告时，可能会以 `engagement` 目标列出。

```bash cURL theme={"system"}
curl -X POST https://api.ayrshare.com/api/ads/instagram/boost \
  -H "Authorization: Bearer API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "postId": "1234567890",
    "accountId": "1234567890",
    "adName": "My Ad",
    "status": "active",
    "goal": "engagement",
    "minAge": 18,
    "maxAge": 65,
    "locations": {"countries": ["US"]},
    "budget": 100,
    "bidAmount": 1,
    "startDate": "2025-03-01T00:00:00Z",
    "endDate": "2025-03-07T23:59:59Z",
    "interests": [1234567890, 1234567891]
  }'
```

```javascript JavaScript theme={"system"}
const API_KEY = "API_KEY";

fetch("https://api.ayrshare.com/api/ads/instagram/boost", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${API_KEY}`
  },
  body: JSON.stringify({
    postId: "1234567890",
    accountId: "1234567890",
    adName: "My Ad",
    status: "active",
    goal: "engagement",
    minAge: 18,
    maxAge: 65,
    locations: { countries: ["US"] },
    budget: 100,
    bidAmount: 1,
    startDate: "2025-03-01T00:00:00Z",
    endDate: "2025-03-07T23:59:59Z",
    interests: [1234567890, 1234567891]
  })
})
  .then((res) => res.json())
  .then((json) => console.log(json))
  .catch(console.error);
```

```python Python theme={"system"}
import requests

API_KEY = "API_KEY"

url = "https://api.ayrshare.com/api/ads/instagram/boost"
payload = {
    "postId": "1234567890",
    "accountId": "1234567890",
    "adName": "My Ad",
    "status": "active",
    "goal": "engagement",
    "minAge": 18,
    "maxAge": 65,
    "locations": {"countries": ["US"]},
    "budget": 100,
    "bidAmount": 1,
    "startDate": "2025-03-01T00:00:00Z",
    "endDate": "2025-03-07T23:59:59Z",
    "interests": [1234567890, 1234567891]
}

response = requests.post(url, headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json=payload)

print(response.json())
```

```php PHP theme={"system"}
<?php
$API_KEY = "API_KEY";

$payload = [
    "postId" => "1234567890",
    "accountId" => "1234567890",
    "adName" => "My Ad",
    "status" => "active",
    "goal" => "engagement",
    "minAge" => 18,
    "maxAge" => 65,
    "locations" => ["countries" => ["US"]],
    "budget" => 100,
    "bidAmount" => 1,
    "startDate" => "2025-03-01T00:00:00Z",
    "endDate" => "2025-03-07T23:59:59Z",
    "interests" => [1234567890, 1234567891]
];

$ch = curl_init("https://api.ayrshare.com/api/ads/instagram/boost");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer " . $API_KEY
]);

$response = curl_exec($ch);
$result = json_decode($response, true);

print_r($result);
curl_close($ch);
```

```csharp C# theme={"system"}
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string API_KEY = "API_KEY";

        var payload = new
        {
            postId = "1234567890",
            accountId = "1234567890",
            adName = "My Ad",
            status = "active",
            goal = "engagement",
            minAge = 18,
            maxAge = 65,
            locations = new { countries = new[] { "US" } },
            budget = 100,
            bidAmount = 1,
            startDate = "2025-03-01T00:00:00Z",
            endDate = "2025-03-07T23:59:59Z",
            interests = new[] { 1234567890, 1234567891 }
        };

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", API_KEY);

        var content = new StringContent(
            JsonSerializer.Serialize(payload),
            Encoding.UTF8,
            "application/json"
        );

        var response = await client.PostAsync("https://api.ayrshare.com/api/ads/instagram/boost", content);
        var responseBody = await response.Content.ReadAsStringAsync();

        Console.WriteLine(responseBody);
    }
}
```

```go Go theme={"system"}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	apiKey := "API_KEY"

	payload := map[string]interface{}{
		"postId":    "1234567890",
		"accountId": "1234567890",
		"adName":    "My Ad",
		"status":    "active",
		"goal":      "engagement",
		"minAge":    18,
		"maxAge":    65,
		"locations": map[string]interface{}{"countries": []string{"US"}},
		"budget":    100,
		"bidAmount": 1,
		"startDate": "2025-03-01T00:00:00Z",
		"endDate":   "2025-03-07T23:59:59Z",
		"interests": []int{1234567890, 1234567891},
	}

	jsonData, err := json.Marshal(payload)
	if err != nil {
		fmt.Println("Error marshaling JSON:", err)
		return
	}

	req, err := http.NewRequest("POST", "https://api.ayrshare.com/api/ads/instagram/boost", bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+apiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	fmt.Println(string(body))
}
```

```java Java theme={"system"}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

public class BoostPost {
    public static void main(String[] args) {
        String API_KEY = "API_KEY";
        String url = "https://api.ayrshare.com/api/ads/instagram/boost";

        Map<String, Object> payload = new HashMap<>();
        payload.put("postId", "1234567890");
        payload.put("accountId", "1234567890");
        payload.put("adName", "My Ad");
        payload.put("status", "active");
        payload.put("goal", "engagement");
        payload.put("minAge", 18);
        payload.put("maxAge", 65);
        payload.put("locations", Map.of("countries", Arrays.asList("US")));
        payload.put("budget", 100);
        payload.put("bidAmount", 1);
        payload.put("startDate", "2025-03-01T00:00:00Z");
        payload.put("endDate", "2025-03-07T23:59:59Z");
        payload.put("interests", Arrays.asList(1234567890, 1234567891));

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String requestBody = objectMapper.writeValueAsString(payload);

            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + API_KEY)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.body());

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
```

```ruby Ruby theme={"system"}
require 'net/http'
require 'uri'
require 'json'

API_KEY = "API_KEY"

uri = URI.parse("https://api.ayrshare.com/api/ads/instagram/boost")
payload = {
  postId: "1234567890",
  accountId: "1234567890",
  adName: "My Ad",
  status: "active",
  goal: "engagement",
  minAge: 18,
  maxAge: 65,
  locations: { countries: ["US"] },
  budget: 100,
  bidAmount: 1,
  startDate: "2025-03-01T00:00:00Z",
  endDate: "2025-03-07T23:59:59Z",
  interests: [1234567890, 1234567891]
}

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

request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "application/json"
request["Authorization"] = "Bearer #{API_KEY}"
request.body = payload.to_json

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

```json 200: Post Boosted theme={"system"}
{
    "status": "success",
    "adId": "120217670757750410",
    "adName": "API Post - DE6gpw8kxlonHy2b7Lo - 2025-03-26T23:42:43",
    "adStatus": "active",
    "bidAmount": 10,
    "budget": 100,
    "endDate": "2026-03-28T22:30:00Z",
    "goal": {
        "title": "Get More Engagement",
        "description": "This goal seeks to increase engagement...",
        "type": "engagement"
    },
    "interests": [
        "6003195554098"
    ],
    "locations": {"countries": ["US"]},
    "maxAge": 65,
    "minAge": 18,
    "postId": "DE6gpw8kxlonHy2b7Lo",
    "socialPostId": "1234567890",
    "igPostId": "1234567890",
    "platform": "instagram",
    "startDate": "2026-03-26T22:30:00Z"
}
```

```json 400: Invalid Account ID theme={"system"}
{
  "action": "boost post",
  "status": "error",
  "code": 369,
  "message": "Unable to boost post. Please try again or contact us if the issue persists.",
  "details": "The accountId likely does not exist. Please check the accountId and try again."
}
```

```json 400: Missing Required Parameters theme={"system"}
{
  "action": "request",
  "status": "error",
  "code": 101,
  "message": "Missing or incorrect parameters. Please verify with the docs. https://www.ayrshare.com/docs/apis",
  "details": "Missing required fields: accountId"
}
```


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