# Getting Started

Source: https://help.brandmachine.shop/api-getting-started/

This guide walks you through your first call to the Brandmachine GraphQL API.

## Prerequisites

Before you begin, you need:

1. A Brandmachine account
2. An API token (see [Authentication](https://help.brandmachine.shop/api-authentication/))
3. A tool to make HTTP requests (cURL, Postman, or code)

The examples below use `YOUR_API_TOKEN` as a placeholder. Replace it with your token.

## Your First Query

Start by asking which team your token belongs to.

### Using cURL

```
curl -X POST https://production.api.brandmachine.shop/graphql \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query { currentTeam { id teamDomain isPAYG } }"
  }'
```

### Using JavaScript

```
async function whoAmI() {
  const response = await fetch('https://production.api.brandmachine.shop/graphql', {
    method: 'POST',
    headers: {
      Authorization: 'Bearer YOUR_API_TOKEN',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: `
        query {
          currentTeam {
            id
            teamDomain
            isPAYG
          }
        }
      `,
    }),
  });

  const result = await response.json();

  if (result.errors) {
    console.error('GraphQL Errors:', result.errors);
    return;
  }

  console.log('Team:', result.data.currentTeam.teamDomain);
}

whoAmI();
```

### Expected Response

```
{
  "data": {
    "currentTeam": {
      "id": "881CB316-F30B-48D6-A928-59CD44421CD8",
      "teamDomain": "your-team",
      "isPAYG": true
    }
  }
}
```

If you get HTTP status `401` instead, the token is missing or not accepted. See [Troubleshooting](https://help.brandmachine.shop/api-authentication/#troubleshooting).

## Useful Read Queries

Once authentication works, a few common starting points (see [Queries](https://help.brandmachine.shop/api-queries/) for the full list with arguments and return types):

```
# List all your library fashion models
query {
  fashionModels {
    id
    name
    gender
  }
}

# List your campaign images
query {
  campaignImages(limit: 10, offset: 0) {
    id
    title
    status
  }
}

# List your Product Studio sessions, most recent first
query {
  getAllProductStudios {
    id
    title
  }
}

# Get the current credit balance and team info
query {
  currentTeam {
    id
    teamDomain
    isPAYG
  }
  creditBalance {
    balanceCents
    currency
  }
}

# Fetch the pay-as-you-go price list
query {
  pricelist {
    label
    tier
    outputUnit
    chargeCents
    currency
  }
}
```

Each price list entry carries its own `label` (the name to show) and `tier`: `generation` is charged per attempt while creating, `release` is charged once when an asset is exported. `outputUnit` says what `chargeCents` buys one of: an `image`, a `video`, or a `second` of video. Use these fields rather than deriving anything from `usageType`.

## Understanding GraphQL Queries

GraphQL lets you request exactly the fields you need:

```
query {
  fashionModels {
    id
    name
    gender
    revisions {
      id
      fullPortraitKey
    }
  }
}
```

**Key concepts:**

- **Operation type:** `query` (read) or `mutation` (write).
- **Fields:** you choose which fields to return.
- **Nested fields:** request related data like `revisions` within `fashionModels`.

## Mutations

Mutations create, change, or delete data. For example, to mark a campaign image result as a favorite:

```
mutation {
  toggleCampaignImageResultFavorite(id: "6c2a...your-uuid") {
    id
    favorite
  }
}
```

See [Mutations](https://help.brandmachine.shop/api-mutations/) for the full list. What a mutation may do depends on your token's role: starting generations needs Creator, releasing and deleting needs Approver. See [Roles and Tokens](https://help.brandmachine.shop/api-authentication/#roles).

## Using Variables

For dynamic queries, use GraphQL variables instead of building the query string yourself:

```
const query = `
  query GetCampaignImage($id: UUID!) {
    campaignImage(id: $id) {
      id
      title
      status
    }
  }
`;

const variables = { id: '6c2a...your-uuid' };

const response = await fetch('https://production.api.brandmachine.shop/graphql', {
  method: 'POST',
  headers: {
    Authorization: 'Bearer YOUR_API_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ query, variables }),
});
```

## Error Handling

Check the HTTP status first, then `result.errors` before using `result.data`:

```
if (response.status === 401) {
  const body = await response.json();
  throw new Error(`Not authenticated: ${body.reason}`);
}

const result = await response.json();

if (result.errors) {
  result.errors.forEach((error) => {
    // Messages look like "Abort.404: Batch not found".
    console.error(`- ${error.message}`);
  });
  return;
}

const data = result.data;
```

A message starting with `Abort.402` means the team's credit balance is too low for a paid generation. Top up in the app before retrying. See [Error Handling](https://help.brandmachine.shop/api-reference/#error-handling) for the other cases.

## Best Practices

### Request Only What You Need

GraphQL returns exactly the fields you ask for. Keep payloads small by selecting only the fields you use.

### Use Fragments

```
fragment ModelBasics on FashionModel {
  id
  name
  gender
}

query {
  fashionModels {
    ...ModelBasics
  }
}
```

### Retry on Transient Errors

Retry network failures and HTTP `5xx` responses with a delay. Do not retry `401` responses or `Abort.4xx` errors unchanged: they fail the same way again.

```
async function fetchWithRetry(query, variables, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch('https://production.api.brandmachine.shop/graphql', {
        method: 'POST',
        headers: {
          Authorization: 'Bearer YOUR_API_TOKEN',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ query, variables }),
      });
      if (response.status >= 500) throw new Error(`Server error ${response.status}`);
      return await response.json();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await new Promise((r) => setTimeout(r, 1000 * (i + 1)));
    }
  }
}
```

## Next Steps

1. **[Explore Queries](https://help.brandmachine.shop/api-queries/)**: full reference of read operations
2. **[Learn Mutations](https://help.brandmachine.shop/api-mutations/)**: write operations
3. **[Review Types](https://help.brandmachine.shop/api-types/)**: object types in the schema
4. **[Upload Files](https://help.brandmachine.shop/api-file-uploads/)**: REST upload endpoints

## Need Help?

Contact [support@brandmachine.shop](mailto:support@brandmachine.shop) with the request payload and the response you got back if something doesn't work.

---

## Other pages

Brandmachine documentation, one Markdown file per page. Index with descriptions: https://help.brandmachine.shop/llms.txt

### Start here

- [Getting Started](https://help.brandmachine.shop/getting-started.md)
- [Input Guidelines](https://help.brandmachine.shop/input-guidelines.md)
- [Billing & Credits](https://help.brandmachine.shop/billing-credits.md)
- [Team Members & Roles](https://help.brandmachine.shop/team-members-roles.md)
- [Shopify App & Web App](https://help.brandmachine.shop/shopify-and-web-app.md)
- [Brandmachine in ChatGPT](https://help.brandmachine.shop/chatgpt.md)

### Product Studio

- [Product Studio](https://help.brandmachine.shop/product-studio-getting-started.md)
- [Aspect Ratios & Custom Crops](https://help.brandmachine.shop/product-studio-aspect-ratios.md)
- [Framing per Garment](https://help.brandmachine.shop/product-studio-framing.md)
- [ZIP Upload](https://help.brandmachine.shop/zip-upload.md)
- [Breuninger Sets](https://help.brandmachine.shop/product-studio-breuninger.md)
- [Delivering to Breuninger](https://help.brandmachine.shop/product-studio-breuninger-delivery.md)
- [Workbench](https://help.brandmachine.shop/workbench.md)

### Campaigns

- [Campaigns](https://help.brandmachine.shop/campaign-composer-getting-started.md)
- [Group Shots](https://help.brandmachine.shop/group-shots.md)
- [Set Locations](https://help.brandmachine.shop/set-locations-getting-started.md)

### Designer

- [Designer](https://help.brandmachine.shop/designer.md)
- [Patterns](https://help.brandmachine.shop/patterns.md)

### Automations

- [Shot Planner](https://help.brandmachine.shop/shot-planner.md)

### Shared Resources

- [Fashion Models](https://help.brandmachine.shop/fashion-models-getting-started.md)
- [Poses](https://help.brandmachine.shop/poses.md)
- [Product Videos](https://help.brandmachine.shop/product-shorts-getting-started.md)
- [Brand Memory](https://help.brandmachine.shop/brand-identity-getting-started.md)
- [Writing a Good Brand Identity](https://help.brandmachine.shop/brand-identity-writing-guide.md)

### Output & Downloads

- [Downloading and Exporting](https://help.brandmachine.shop/downloading-and-exporting.md)
- [AI Metadata on Downloads](https://help.brandmachine.shop/ai-metadata.md)
- [Content Credentials and C2PA Conformance](https://help.brandmachine.shop/content-credentials.md)
- [Photo Editor](https://help.brandmachine.shop/photo-editor.md)

### Developers

- [API Reference](https://help.brandmachine.shop/api-reference.md)
- [Authentication](https://help.brandmachine.shop/api-authentication.md)
- [Exporting Released Images](https://help.brandmachine.shop/api-exporting-images.md)
- [File Uploads](https://help.brandmachine.shop/api-file-uploads.md)
- [Importing Size Charts](https://help.brandmachine.shop/api-size-charts.md)
- [Queries](https://help.brandmachine.shop/api-queries.md)
- [Mutations](https://help.brandmachine.shop/api-mutations.md)
- [Types](https://help.brandmachine.shop/api-types.md)
- [Input Types](https://help.brandmachine.shop/api-input-types.md)
- [Enums](https://help.brandmachine.shop/api-enums.md)
- [Scalars](https://help.brandmachine.shop/api-scalars.md)
