Setting up APIs

JavaScript
const BRANDFETCH_SECRET_API_KEY = "..."

async function brandApi(domain) {
  const response = await fetch(
    `https://api.brandfetch.io/v2/brands/${domain}`,
    { method: 'GET', headers: { 'authorization': `Bearer ${BRANDFETCH_SECRET_API_KEY}` } }
  )

  return response.json()
}

async function graphql(query, variables) {
  const response = await fetch(
    `https://graphql.brandfetch.io/`,
    { method: 'POST', headers: { 'authorization': `Bearer ${BRANDFETCH_SECRET_API_KEY}` } }
  )

  return response.json()
}

Create a Webhook

Create a new webhook with the createWebhook mutation. You can subscribe to receive updates on multiple brands on a single webhook.

JavaScript
const webhookEndpointUrl = 'https://your-website.com/webhook'

const { data: { createWebhook: { webhook } } } = await graphql(`
  mutation CreateWebhook($createInput: CreateWebhookInput!) {
    createWebhook(input: $createInput) {
      code
      message
      success
      webhook {
        urn
      }
    }
  }
`,
	{
  	createInput: {
    	description: 'Brand updates',
	    enabled: true,
  	  events: ['brand.updated'],
    	url: webhookEndpointUrl
	  }
})

Retrieve a brand

We need to retrieve the brand to get it’s URN (ID). Typically you’ll have already made an initial request to fetched a brand — and now you want to continue to receive updates on it.

JavaScript
const brand = await brandApi('brandfetch.com')

Subscribe to brand updates

To subscribe to a brand’s data updates, we can use the addWebhookSubscriptions mutation to add the brand to the list of active subscriptions on the webhook. We can subscribe to one or more brands at once with this mutation by passing the each brand’s URN in the subscriptions list variable.

JavaScript
await graphql(`
  mutation AddWebhookSubscriptions($webhookUrn: URN!, $subscriptions: [URN!]!)
    addWebhookSubscriptions(webhook: $webhookUrn, subscriptions: $subscriptions) {
      code
      message
      success
    }
  }
`,
	{
  	webhookUrn: webhook.urn,
  	subscriptions: [brand.urn]
})

Unsubscribe a subscription

If we later wish to unsubscribe from a brand we can do so with the removeWebhookSubscriptions mutation. Like the addWebhookSubscriptions mutation, here we can remove multiple URNs at once by providing them as part of the subscriptions list variable.

JavaScript
await graphql(`
  mutation RemoveWebhookSubscriptions($webhookUrn: URN!, $subscriptions: [URN!]!)
    removeWebhookSubscriptions(webhook: $webhookUrn, subscriptions: $subscriptions) {
      code
      message
      success
    }
  }
`,
	{
  	webhookUrn: webhook.urn,
  	subscriptions: [brand.urn]
})