> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.afternoon.co/llms.txt.
> For full documentation content, see https://docs.afternoon.co/llms-full.txt.

# Create a credit grant on a subscription

POST https://api.afternoon.co/v1/subscriptions/{id}/credit-grants
Content-Type: application/json

Grants credits to a subscription. Provide either pricing_unit_id for pricing-unit credits or currency_code for currency credits.

Reference: https://docs.afternoon.co/api-reference/afternoon-events-api/subscriptions/create-credit-grant

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: Afternoon Events API
  version: 1.0.0
paths:
  /v1/subscriptions/{id}/credit-grants:
    post:
      operationId: create-credit-grant
      summary: Create a credit grant on a subscription
      description: >-
        Grants credits to a subscription. Provide either pricing_unit_id for
        pricing-unit credits or currency_code for currency credits.
      tags:
        - subpackage_subscriptions
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: cuid
        - name: Authorization
          in: header
          description: API key obtained from the Afternoon dashboard
          required: true
          schema:
            type: string
      responses:
        '201':
          description: Credit grant created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreditGrantResponse'
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          description: Credit grant not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateCreditGrantRequest'
servers:
  - url: https://api.afternoon.co
  - url: http://localhost:8787
components:
  schemas:
    CreateCreditGrantRequestAmount:
      oneOf:
        - type: number
          format: double
        - type: string
      description: Credit amount (positive value). Accepts a number or numeric string.
      title: CreateCreditGrantRequestAmount
    CreateCreditGrantRequest:
      type: object
      properties:
        name:
          type: string
          description: Display name for the credit grant
        amount:
          $ref: '#/components/schemas/CreateCreditGrantRequestAmount'
          description: Credit amount (positive value). Accepts a number or numeric string.
        pricing_unit_code:
          type: string
          description: >-
            Pricing unit code (e.g. "gpu_sec", "token"). Required when granting
            pricing-unit credits.
        currency_code:
          type: string
          description: Currency code (e.g. "usd"). Required when granting currency credits.
        expires_at:
          type:
            - string
            - 'null'
          format: date-time
          description: ISO 8601 expiration date, or null for no expiry
      required:
        - name
        - amount
      title: CreateCreditGrantRequest
    CreditGrantAccountType:
      type: string
      enum:
        - pricing_unit
        - currency
      title: CreditGrantAccountType
    CreditGrantStatus:
      type: string
      enum:
        - pending
        - active
        - voided
      title: CreditGrantStatus
    CreditGrant:
      type: object
      properties:
        id:
          type: string
        customer_id:
          type: string
        subscription_id:
          type:
            - string
            - 'null'
        account_type:
          $ref: '#/components/schemas/CreditGrantAccountType'
        pricing_unit_id:
          type:
            - string
            - 'null'
        currency_code:
          type:
            - string
            - 'null'
        name:
          type: string
        amount:
          type: string
          description: Total grant amount as a decimal string
        balance:
          type: string
          description: Remaining balance as a decimal string
        status:
          $ref: '#/components/schemas/CreditGrantStatus'
        expires_at:
          type:
            - string
            - 'null'
        created_at:
          type: string
        updated_at:
          type: string
      required:
        - id
        - customer_id
        - subscription_id
        - account_type
        - pricing_unit_id
        - currency_code
        - name
        - amount
        - balance
        - status
        - expires_at
        - created_at
        - updated_at
      title: CreditGrant
    CreditGrantResponse:
      type: object
      properties:
        success:
          type: boolean
        credit_grant:
          $ref: '#/components/schemas/CreditGrant'
        request_id:
          type: string
      required:
        - success
        - credit_grant
        - request_id
      title: CreditGrantResponse
    ErrorResponseError:
      type: object
      properties:
        code:
          type: string
        message:
          type: string
        details:
          oneOf:
            - description: Any type
            - type: 'null'
      required:
        - code
        - message
      title: ErrorResponseError
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
        error:
          $ref: '#/components/schemas/ErrorResponseError'
        request_id:
          type: string
          description: Request ID for tracing
      required:
        - success
        - error
      title: ErrorResponse
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: API key obtained from the Afternoon dashboard

```

## SDK Code Examples

```typescript
import { AfternoonClient } from "afternoon-sdk";

async function main() {
    const client = new AfternoonClient({
        token: "YOUR_TOKEN_HERE",
    });
    await client.subscriptions.createCreditGrant("cm5x9z8nv0000h85r7l9p2k1m", {
        name: "Onboarding credits",
        amount: 1000,
    });
}
main();

```

```python
import requests

url = "https://api.afternoon.co/v1/subscriptions/cm5x9z8nv0000h85r7l9p2k1m/credit-grants"

payload = {
    "name": "Onboarding credits",
    "amount": 1000
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```go
package main

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

func main() {

	url := "https://api.afternoon.co/v1/subscriptions/cm5x9z8nv0000h85r7l9p2k1m/credit-grants"

	payload := strings.NewReader("{\n  \"name\": \"Onboarding credits\",\n  \"amount\": 1000\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

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

url = URI("https://api.afternoon.co/v1/subscriptions/cm5x9z8nv0000h85r7l9p2k1m/credit-grants")

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

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"name\": \"Onboarding credits\",\n  \"amount\": 1000\n}"

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

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.afternoon.co/v1/subscriptions/cm5x9z8nv0000h85r7l9p2k1m/credit-grants")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"name\": \"Onboarding credits\",\n  \"amount\": 1000\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.afternoon.co/v1/subscriptions/cm5x9z8nv0000h85r7l9p2k1m/credit-grants', [
  'body' => '{
  "name": "Onboarding credits",
  "amount": 1000
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.afternoon.co/v1/subscriptions/cm5x9z8nv0000h85r7l9p2k1m/credit-grants");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"name\": \"Onboarding credits\",\n  \"amount\": 1000\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "name": "Onboarding credits",
  "amount": 1000
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.afternoon.co/v1/subscriptions/cm5x9z8nv0000h85r7l9p2k1m/credit-grants")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```